简体   繁体   English

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

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

I am trying to run my Dijkstra function twice so that I can figure out the shortest distance between 3 points.我正在尝试运行我的 Dijkstra function 两次,以便找出 3 点之间的最短距离。 It works fine when I run it once, but two times returns a key error on line 38 and 44.当我运行一次时它工作正常,但两次在第 38 行和第 44 行返回一个关键错误。

Code:代码:

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')

Here is the error I get:这是我得到的错误:

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'

When you do unseenNodes = graph you bind the variable unseenNodes to the same dict referenced by graph .当您执行unseenNodes = graph时,您将变量unseenNodes绑定到graph引用的同一个dict 。

That means that any changes done on unseenNodes will reflect also on graph .这意味着对unseenNodes所做的任何更改也将反映在graph

So, in the first dijkstra(graph, 'L1', 'c2') all goes good and well.因此,在第一个dijkstra(graph, 'L1', 'c2')中一切顺利。

BUT , during that run you executed some unseenNodes.pop(minNode) which again, are equivalent to doing graph.pop(minNode) .但是,在那次运行期间,您执行了一些unseenNodes.pop(minNode) ,这再次等同于执行graph.pop(minNode) So by the time you do dijkstra(graph, 'c2', 'c3') your graph has changed and doesn't look like you think it does.因此,当您执行dijkstra(graph, 'c2', 'c3')您的图表已经改变并且看起来不像您认为的那样。 This is why it works when running only once.这就是为什么它只运行一次时起作用的原因。

The easy remedy is to work on a copy of graph to make sure it stays intact.简单的补救措施是处理graph的副本以确保它保持完整。 All you need to do is change the assignment to: unseenNodes = dict(graph) .您需要做的就是将分配更改为: unseenNodes = dict(graph) This creates a copy of graph ( unseenNodes now references another separate dict, and not the one referenced by graph ).这会创建一个graph副本unseenNodes现在引用另一个单独的 dict,而不是graph引用的那个)。

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

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