在线看到这个例子,它是一个dfs函数,可以找到图形中的所有周期。
我试图将循环部分添加到函数中,因此我不必使用shell来获得结果。 我是发电机对象的新手,所以我不确定如何显示周期。
使用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
有什么想法吗?
答案 0 :(得分:2)
这是你在找什么?
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)
你不需要在生成器中返回,所以你可以使用列表推导或常规循环来循环它。
答案 1 :(得分:0)
首先,请修改你的缩进。
我认为你的问题是缺少[]
列表理解工作的结果。
尝试更改线路
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)]