【发布时间】: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函数中使用yield和return??
标签: python graph depth-first-search brute-force function-calls