我正在尝试制作一个"路径查找器"
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__'
有人可以帮我把这件事搞定吗
答案 0 :(得分:2)
有几个尴尬和错误:
使用None
而不是使用列表初始化 path 参数。
并在函数体中创建空列表。
def find_all_paths(start, end, graph, path=None):
path = path or []
传递给find_all_paths
的值不尊重签名。
写下这个:
newpaths = find_all_paths(node, end, graph, path)
由于值为整数,因此图表必须包含int
而不是strings
。
graph = {1: [2], 2: [3, 4, 5], 3: [4], 4: [5, 6], 5: [], 6: []}
以下是您的代码的固定版本:
def find_all_paths(start, end, graph, path=None):
path = path or []
path.append(start)
if start == end:
return [path]
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(node, end, graph, path)
for newpath in newpaths:
paths.append(newpath)
return paths
如果您尝试这样做:
graph = {1: [2], 2: [3, 4, 5], 3: [4], 4: [5, 6], 5: [], 6: []}
print(find_all_paths(2, 5, graph))
你会得到:
[[2, 3, 4, 5, 6]]