繁体   English   中英

为什么我会收到此密钥错误? (Python)

[英]Why am I getting this Key error? (Python)

我正在尝试运行我的 Dijkstra function 两次,以便找出 3 点之间的最短距离。 当我运行一次时它工作正常,但两次在第 38 行和第 44 行返回一个关键错误。

代码:

graph = {'c1': {'c2':4, 'L1':3}, 'c2':{'c1':4, 'c3':3, 'L1':2.5}, 'c3':{'c2':3, 'L1':2}, 'L1':{'c1':3, 'c2':2.5, 'c3':2}}

def dijkstra(graph, start, goal):
    shortest_distance = {}
    predecessor = {}
    unseenNodes = graph
    infinity = float('inf')
    path = []

    for node in unseenNodes:
        shortest_distance[node] = infinity
    shortest_distance[start] = 0
    #print(shortest_distance)

    while unseenNodes:
        minNode = None
        for node in unseenNodes:
            if minNode is None:
                minNode = node
            elif shortest_distance[node] < shortest_distance[minNode]:
                minNode = node
        for childNode, weight in graph[minNode].items():
            if weight + shortest_distance[minNode] < shortest_distance[childNode]:
                shortest_distance[childNode] = weight + shortest_distance[minNode]
                predecessor[childNode] = minNode
        unseenNodes.pop(minNode)

    currentNode = goal
    while currentNode != start:
        try:
            path.insert(0, currentNode)
            currentNode = predecessor[currentNode]
        except KeyError:
            print('Path not reachable')
            break
    path.insert(0, start)

    if shortest_distance[goal] != infinity:
        print('Shortest distance: ' + str(shortest_distance[goal]))
        print('Path:' + str(path))

dijkstra(graph, 'L1', 'c2')
dijkstra(graph, 'c2', 'c3')

这是我得到的错误:

Path not reachable
    dijkstra(graph, 'c2', 'c3')
  File "E:\Work\Delivery_API\Delivery.py", line 38, in dijkstra
    if shortest_distance[goal] != infinity:
KeyError: 'c3'

当您执行unseenNodes = graph时,您将变量unseenNodes绑定到graph引用的同一个dict 。

这意味着对unseenNodes所做的任何更改也将反映在graph

因此,在第一个dijkstra(graph, 'L1', 'c2')中一切顺利。

但是,在那次运行期间,您执行了一些unseenNodes.pop(minNode) ,这再次等同于执行graph.pop(minNode) 因此,当您执行dijkstra(graph, 'c2', 'c3')您的图表已经改变并且看起来不像您认为的那样。 这就是为什么它只运行一次时起作用的原因。

简单的补救措施是处理graph的副本以确保它保持完整。 您需要做的就是将分配更改为: unseenNodes = dict(graph) 这会创建一个graph副本unseenNodes现在引用另一个单独的 dict,而不是graph引用的那个)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM