【发布时间】:2014-02-06 13:05:53
【问题描述】:
我正在尝试在图表中查找游览。我已经编写了以下代码,这似乎可以正确打印旅行。我希望它在找到第一个游览后停止并将游览作为列表返回。但是,递归堆栈似乎完成了,我没有得到想要的结果。当我找到第一个游览(即满足我的条件)时,如何返回一个值并完全停止递归?谢谢。
def get_tour(start, graph, path):
if path==[]:
from_node=start
else:
from_node=path[-1][1]
if graph==[]:
if start in path[-1]:
print "Tour Found"
return path
else:
edges=[node for node in graph if from_node in node]
for edge in edges:
to_node=[i for i in edge if i<> from_node][0]
p=list(path)
p.append((from_node,to_node))
g=list(graph)
g.remove(edge)
get_tour(start, g,p)
g=[(1,2), (1,3), (2,3)]
get_tour(1, graph=g, path=[])
【问题讨论】:
-
那么,如果
get_tour(start, g,p)不是None,您为什么不直接返回return,而不是继续滚动循环? -
我不完全理解为什么部分,但你的建议有效。如果我说 a=get_tour(start, g,p) if (a): return a.谢谢!我会根据自己的理解努力。
-
不完全理解这个问题,但我想如果你找到一个旅游,你想
break在循环中。另外我认为您需要以某种方式返回最后一个else块的结果。
标签: python recursion conditional