簡體   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