ValueError:实现广度优先搜索时的字典更新序列元素

时间:2016-11-10 12:11:14

标签: python dictionary shortest-path breadth-first-search

我正在尝试将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'}}

Python程序

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

我尝试了什么:

  1. dictionary update sequence element #0 has length 3; 2 is required

  2. Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

  3. 请随时建议任何更好的方法来实现这一目标。请不要建议更改我的数据结构(这是一项要求)。

1 个答案:

答案 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]))