简体   繁体   English

如何解决dfs、bfs中的KeyError

[英]How to solve KeyError in dfs, bfs

I was trying to create bfs, dfs programs by using the following python code.我试图通过使用以下 python 代码来创建 bfs、dfs 程序。 Unfortunately having this error...... anybody plz help for me不幸的是有这个错误......任何人请帮助我

Traceback (most recent call last): File "D:...\1260.py", line 35, in print(dfs(graph, 1)) File "D:...\1260.py", line 30, in dfs stack.extend(graph[node]) KeyError: 4回溯(最后一次调用):文件“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])

You have no node key in the graph .您在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