当在Python中遍历一个图时,我收到这个错误:
'dict'对象没有has_key属性
这是我的代码:
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not graph.has_key(start):
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
该代码旨在查找从一个节点到其他节点的路径。代码来源:http://cs.mwsu.edu/~terry/courses/4883/lectures/graphs.html
为什么我得到这个错误,我该如何解决它?
文档中的整个代码将是:
graph = {'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']}
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
写完后,保存文档并按f5
在那之后,你将在Python IDLE shell中运行的代码将是:
find_path(图,' A ', ' D ')
您应该在IDLE中收到的答案是
['A', 'B', 'C', 'D']
文档中的整个代码将是:
graph = {'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']}
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
写完后,保存文档并按f5
在那之后,你将在Python IDLE shell中运行的代码将是:
find_path(图,' A ', ' D ')
您应该在IDLE中收到的答案是
['A', 'B', 'C', 'D']