【发布时间】:2017-05-15 13:57:02
【问题描述】:
我正在尝试做一个“路径查找器”
def find_all_paths(start, end, graph, path=[]):
path = path + [start]
if start == end:
return [path]
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
graph={1: ['2'], 2: ['3', '4', '5'], 3: ['4'], 4: ['5', '6'], 5: [], 6: []}
如果我在 shell 中输入 find_all_paths(2,5,graph) 我应该取回从图形字典中的键 2 到 5 值的所有路径
一个正确的结果应该是这样的
path=[[2,5],[2,3,4,5][2,4,5]]
代码不断给出值错误,例如
for node in graph[start]:
TypeError: 'int' object has no attribute '__getitem__'
有人可以帮我把这个东西运行起来
【问题讨论】:
-
您应该避免使用像
list这样的可变值来初始化参数。请参阅《Python 漫游指南》中的 Common Gotchas! -
使用
print()检查您在graph中的内容 - 似乎您分配的是单个数字而不是列表或目录。 -
递归调用错误:传递的参数不尊重参数。替换为:
newpaths = find_all_paths(node, end, graph, path).
标签: python python-2.7 typeerror