我尝试在 jupyter 笔记本(python 版本 - 3.7.6)上运行的代码有一个奇怪的问题
此链接中的代码 ( https://towardsdatascience.com/to-all-data-scientists-the-one-graph-algorithm-you-need-to-know-59178dbb1ec2 ) 由于 python 而有点过时它所写的版本。我将“.iteritems”更改为“.items”并且在这部分之前效果很好:
graph = Graph(g)
graph.add_edge(("Mumbai", "Delhi"),400)
graph.add_edge(("Delhi", "Kolkata"),500)
graph.add_edge(("Kolkata", "Bangalore"),600)
graph.add_edge(("TX", "NY"),1200)
graph.add_edge(("ALB", "NY"),800)
g = graph.adj_mat()
def bfs_connected_components(graph):
connected_components = []
nodes = graph.keys()
while len(nodes)!=0:
start_node = nodes.pop()
queue = [start_node] #FIFO
visited = [start_node]
while len(queue)!=0:
start = queue[0]
queue.remove(start)
neighbours = graph[start]
for neighbour,_ in neighbours.items():
if neighbour not in visited:
queue.append(neighbour)
visited.append(neighbour)
nodes.remove(neighbour)
connected_components.append(visited)
return connected_components
print bfs_connected_components(g)
它给了我这个错误File "<ipython-input-48-660b0e10e666>", line 32 print bfs_connected_components(g) ^ SyntaxError: invalid syntax
所以我试着起飞print,只是bfs_connected_components(g)为了找到调试器会返回给我的东西。
当我在没有命令的情况下运行代码时,print它会返回以下错误:
AttributeError Traceback (most recent call last)
<ipython-input-49-09c142e436e3> in <module>
30 return connected_components
31
---> 32 bfs_connected_components(g)
<ipython-input-49-09c142e436e3> in bfs_connected_components(graph)
14
15 while len(nodes)!=0:
---> 16 start_node = nodes.pop()
17 queue = [start_node] #FIFO
18 visited = [start_node]
AttributeError: 'dict_keys' object has no attribute 'pop'
这很奇怪,因为此链接中的先前代码中有.pop命令,并且它运行良好,没有任何错误,除了表达式.iteritems。
摇曳的蔷薇
相关分类