[英]'NoneType' object is not iterable error in Python
我试图在路径列表中找到最短的列表,但我收到一个错误('NoneType' object 在 Python 中是不可迭代的错误)。 此 function 用于“图形模式”或“搜索算法”,用于寻找到达目标的最短路径。 请让我知道我在这里做错了什么。 谢谢!
graph = {'A':['B','C'],'B':['F','D','I'],'C':['D','E','G'],'D':['H'],'F':['I'],'E':['G'],'I':['H'],'D':['H'],'H':['G']}
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in graph:
return []
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)
minList=min(paths, key= len)
print(minList)
顶点G
已从您的邻接列表中丢失。 修改邻接列表并从 function 返回paths
后,您将能够得到正确的结果
graph = {'A':['B','C'],'B':['F','D','I'],'C':['D','E','G'],'D':['H'],'F':['I'],'E':['G'],'I':['H'],'D':['H'],'H':['G'], 'G':[]}
def find_all_paths(graph, start, end, 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)
if newpaths:
for newpath in newpaths:
paths.append(newpath)
return paths
graph
{'A': ['B', 'C'],
'B': ['F', 'D', 'I'],
'C': ['D', 'E', 'G'],
'D': ['H'],
'F': ['I'],
'E': ['G'],
'I': ['H'],
'H': ['G'],
'G': []}
paths = find_all_paths(graph,'A', 'H',[])
Output:
paths
[['A', 'B', 'F', 'I', 'H'],
['A', 'B', 'D', 'H'],
['A', 'B', 'I', 'H'],
['A', 'C', 'D', 'H']]
为了找到最短路径之一,您可以使用
min(paths, key=len)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.