我正在尝试将Breadth First Search移植到输入图形作为字典值的字典:
graph = {'A': {'B':'B', 'C':'C'},
'B': {'A':'A', 'D':'D', 'E':'E'},
'C': {'A':'A', 'F':'F'},
'D': {'B':'B'},
'E': {'B':'B', 'F':'F'},
'F': {'C':'C', 'E':'E'}}
def dictSub(d1,d2):
return {key: d1[key] - d2.get(key, 0) for key in d1.keys()}
def bfs_paths(graph, start, goal):
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for next in dictSub(graph[vertex], dict(zip([path,path]))):
# print graph[vertex] - set(path)
print graph[vertex]
print set(path)
print vertex
raw_input()
if next == goal:
yield path + [next]
else:
queue.append((next, path + [next]))
def shortest_path(graph, start, goal):
try:
return next(bfs_paths(graph, start, goal))
except StopIteration:
return None
print shortest_path(graph, 'A', 'F') # ['A', 'C', 'F']
所以这是来自this tutorial的源代码。如果使用原始源代码,它运行良好。当我试图实现这个时,我遇到了:
Traceback (most recent call last):
File "./bfsTest.py", line 66, in <module>
print shortest_path(graph, 'A', 'F') # ['A', 'C', 'F']
File "./bfsTest.py", line 62, in shortest_path
return next(bfs_paths(graph, start, goal))
File "./bfsTest.py", line 49, in bfs_paths
for next in dictSub(graph[vertex], dict(zip([path,path]))):
ValueError: dictionary update sequence element #0 has length 1; 2 is required
dictionary update sequence element #0 has length 3; 2 is required
Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4
答案 0 :(得分:0)
错误来自dict(zip([path, path]))
,应为dict(zip(path, path))
此外,您的dictSub
功能应如下所示:
def dictSub(d1,d2):
return {key: d1[key] for key in d1.keys() if key not in d2}
或者,您可以使用set arithmetics简化代码
def bfs_paths(graph, start, goal):
graph = {k: set(v) for k, v in graph.items()}
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for next in (graph[vertex] - set(path)):
if next == goal:
yield path + [next]
else:
queue.append((next, path + [next]))