簡體   English   中英

如何解決dfs、bfs中的KeyError

[英]How to solve KeyError in dfs, bfs

我試圖通過使用以下 python 代碼來創建 bfs、dfs 程序。 不幸的是有這個錯誤......任何人請幫助我

回溯(最后一次調用):文件“D:...\1260.py”,第 35 行,在 print(dfs(graph, 1)) 文件“D:...\1260.py”,第 30 行,在 dfs stack.extend(graph[node]) KeyError: 4

graph = {
    1: [2, 3, 4],
    2: [4],
    3: [4]
}

def bfs(graph, start_node):
    visit = list()
    queue = list()

    queue.append(start_node)
    while queue:
        node = queue.pop(0)
        if node not in visit:
            visit.append(node)
            queue.extend(graph[node])
            
    return visit

def dfs(graph, start_node):
    visit = list()
    stack = list()

    stack.append(start_node)

    while stack:
        node = stack.pop()
        if node not in visit:
            visit.append(node)
            stack.extend(graph[node])

    return visit

if '__main__' == __name__:
    print(dfs(graph, 1))
    print(bfs(graph, 1))
stack.extend(graph[node])

您在graph中沒有node鍵。

try:
    stack.extend(graph[node])
except KeyError:
    print(f"Unexpected node: {node}")

暫無
暫無

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

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