【问题标题】:how can i print out the generator object without using the shell?如何在不使用 shell 的情况下打印生成器对象?
【发布时间】:2018-04-18 14:52:42
【问题描述】:

在网上看到了这个例子,它是一个 dfs 函数,可以找到图中的所有循环。

我正在尝试将循环部分添加到函数中,这样我就不必使用 shell 来获取结果。 我是生成器对象的新手,所以我不确定如何显示周期。

使用外壳的版本:

def dfs(graph, start, end):
    fringe = [(start, [])]
    while fringe:
        state, path = fringe.pop()
        if path and state == end:
            yield path
            continue
    for next_state in graph[state]:
        if next_state in path:
            continue
        fringe.append((next_state, path+[next_state]))

>>> graph = { 1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2] }
>>> cycles = [[node]+path  for node in graph for path in dfs(graph, node, node)]
>>> len(cycles)
7
>>> cycles
[[1, 5, 2, 1], [1, 3, 1], [1, 2, 1], [2, 1, 5, 2], [2, 1, 2], [3, 1, 3], [5, 2, 1, 5]]

这是我的尝试:

def dfs(g, start, end):
    fringe = [(start, [])]
    while fringe:
        state, path = fringe.pop()
        if path and state == end:
            yield path
            continue
    for next_state in g[state]:
        if next_state in path:
            continue
        fringe.append((next_state, path+[next_state]))
    cycles = (list([node]+path for node in g for path in dfs(g, node, node)))
    print("cycles",cycles)
return path

dfs(graph, 1, 1)

尝试了几个不同的开始和结束节点,结果都一样。

我的图和上面一样,

 graph = { 1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2] }

输出 = 生成器对象 dfs 位于 0x000001D9CB846EB8

有什么想法吗?

【问题讨论】:

  • 如果您使用list() 将生成器投射到列表中,则可以照常打印该列表。请注意,强制转换将评估整个生成器对象,这意味着您将失去对生成器的惰性评估。
  • 也可以print(*your_generator) 使用*splat 运算符。
  • @chrisz 但它会消耗它。
  • 你能修正你的缩进吗?
  • 等等:你在dfs函数中使用yieldreturn??

标签: python graph depth-first-search brute-force function-calls


【解决方案1】:

这是你要找的吗?

def dfs(g, start, end):
    fringe = [(start, [])]
    while fringe:
        state, path = fringe.pop()
        if path and state == end:

            yield path
            continue
        for next_state in g[state]:
            if next_state in path:
                continue
            fringe.append((next_state, path+[next_state]))


graph = {1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2]}
cycles = [[node]+path for node in graph for path in dfs(graph, node, node)]
print(cycles)

您不需要在生成器中返回,因此您可以使用列表推导式或常规循环来循环它。

【讨论】:

    【解决方案2】:

    首先,请修正你的缩进。

    我认为您的问题是缺少 [] 以使列表理解起作用的结果。

    尝试换行 cycles = (list([node]+path for node in g for path in dfs(g, node, node)))cycles = [[node]+path for node in g for path in dfs(g, node, node)]

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2015-05-22
      相关资源
      最近更新 更多