python - python 中的 dfs 不工作请指导我有关错误

标签 python algorithm python-3.x dictionary

def dfs(graph, start, visited=None):

    if visited is None:
        visited = set()
    if start in visited:
        return
    visited.add(start)
    for a in graph[start]:
        if a not in visited:
            dfs(graph, a, visited)
    return visited
graph={'A':['B'],'B':['C']}

b=dfs(graph,'A')

print(b)

最佳答案

graph[start] 将提高 KeyError如果 start 不在字典中。您可以将其替换为 dict.get返回默认值(空序列):

def dfs(graph, start, visited=None):
    if visited is None:
        visited = set()
    if start in visited:
        return
    visited.add(start)
    for a in graph.get(start, []):  # <---
        if a not in visited:
            dfs(graph, a, visited)
    return visited

关于python - python 中的 dfs 不工作请指导我有关错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34453876/

相关文章:

python - 使用正则表达式删除不需要的字符串结尾

python 正则表达式模式在字符串中不匹配,甚至在测试器中匹配(重试,正则表达式教练,http ://ksamuel. pythonanywhere.com)

algorithm - Z3中使用的DPLL(T)算法(线性算法)

python - 尝试使用递归方法生成字符串的子集

python - urllib 上缺少方法

Python pickle 调用 cPickle?

python - 向 Django 应用程序添加简单搜索

python - Android 应用程序数据库与远程数据库同步

algorithm - 在散列算法之上使用另一种算法

python - 将多种算法与 sklearn 管道进行比较