繁体   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