【发布时间】:2019-04-29 20:28:41
【问题描述】:
我是 python 新手。我尝试使用 BFS 获得 Unweighted-Single-Source-Shortest-Path。
from queue import *
def ussp(graph, s):
len_graph = len(graph)
prev = [[]*len_graph for i in range(len_graph)]
visited = [False for i in range(len_graph)]
queue2 = Queue
dist = [[float('inf')] for i in range(len_graph)]
queue2.put_nowait(graph[s], 0) # starting with s
visited[s] = True
dist[s] = 0
# modified BFS alg.
while queue2.empty() == False:
h = queue2.get_nowait()
for i in len(graph[h]):
if visited[graph[h][i]] == False:
visited[graph[h][i]] = True
dist[graph[h][i]] = dist[h] + 1
prev[graph[h][i]] = h
queue2.put_nowait(graph[h][i], 0)
print(dist)
graph2 = {1: [2, 3, 5], 2: [4, 6, 1], 3: [5, 1], 4: [6], 5: [2], 6: [1, 7], 7: [2]}
ussp(graph2, 1)
这就是我现在得到的。我很确定它应该工作,但它根本没有。它甚至没有被编译。我对 python 中的列表、数组和队列也很陌生。如果你能帮助我,那就太好了。提前致谢
【问题讨论】:
-
两件事:首先,在 Python 中使用
from <package> import *被认为是不好的做法,因为它使调试变得非常困难。其次,在 SO 上发布您的回溯/错误消息会很有帮助,以便人们可以看到问题所在。 -
错误是什么?
-
当然。以下是错误:
Traceback (most recent call last): File "C:/Users/svenp/PycharmProjects/or3/or4.py", line 27, in <module> ussp(graph2, 1) File "C:/Users/svenp/PycharmProjects/or3/or4.py", line 10, in ussp queue2.put_nowait(graph[s], 0) # starting with s File "C:\Users\svenp\AppData\Local\Programs\Python\Python36\lib\queue.py", line 184, in put_nowait return self.put(item, block=False) AttributeError: 'list' object has no attribute 'put'
标签: python shortest-path breadth-first-search