簡體   English   中英

發生異常:KeyError 'h' File "C:\Users\username\Downloads\test.py", line 19, in dfs, 如何修復?

[英]Exception has occurred: KeyError 'h' File "C:\Users\username\Downloads\test.py", line 19, in dfs, how to fix?

# Python dictionary to act as an adjacency list
graph = {
  'a' : ['b','c'],
  'b': ['d', 'e'],
  'd': ['h','i'],
  'e': ['j', 'k'],
  'c' : ['f','g'],
  'g': ['l','m']
}

visited = [] # List of visited nodes of graph.
def dfs(visited, graph, node):
    
    if node not in visited:
        visited.append(node)
    

    for neighbor in graph[node]:
        dfs(visited, graph, neighbor)
    print(node)

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, "a")
print("visited=",visited)

我該如何解決這個錯誤。

這是一棵樹。 為了形象化,您需要知道 a 有兩個孩子 b 和 c。

b 有 2 個孩子 d 和 e

d 有 2 個孩子 h 和 i

e 有 2 個孩子 j 和 k 等等。

我運行了一個類似的代碼,但這些圖中的數字是 7,8 等,而不是 a,b,c。 它運行完美。 但在這種情況下,它沒有運行。 你能調試一下嗎

您不能從葉節點下降。 葉節點沒有子節點,因此不是graph字典中的鍵。

...
    for neighbor in graph[node]:
        if neighbor in graph.keys():  #not leaf
            dfs(visited, graph, neighbor)
        else
            visited.append(neighbor)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM