You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python生成节点间所有路径程序报错求助:UnboundLocalError

解决UnboundLocalError: local variable 'newpaths' referenced before assignment错误

问题原因

你的代码中,当遍历到已经存在于当前path中的节点时,newpaths变量未被初始化就直接在for循环中被引用。例如递归到节点e时,它的邻接节点是b,而b已经在当前路径里,此时if node not in path条件不成立,newpaths没有被赋值,后续执行for newpath in newpaths就会触发未定义错误。

修复后的代码

写法一:调整代码块范围

graph = { 
    "a" : ["b","c"],
    "b" : ["a", "d"],
    "c" : ["a", "d"],
    "d" : ["e"],
    "e" : ["b"]
}

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    paths = []
    for node in graph[start]:
        if node not in path:
            newpaths = find_all_paths(graph, node, end, path)
            for newpath in newpaths:
                paths.append(newpath)
    return paths

print(find_all_paths(graph, "b","e"))

写法二:用extend简化逻辑(更推荐)

graph = { 
    "a" : ["b","c"],
    "b" : ["a", "d"],
    "c" : ["a", "d"],
    "d" : ["e"],
    "e" : ["b"]
}

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    paths = []
    for node in graph[start]:
        if node not in path:
            # 直接将递归返回的路径列表合并到paths中
            paths.extend(find_all_paths(graph, node, end, path))
    return paths

print(find_all_paths(graph, "b","e"))

修复说明

  • 写法一:将for newpath in newpaths移到if条件块内部,确保只有节点不在路径中时才执行递归和路径添加,避免引用未定义变量。
  • 写法二:使用extend方法直接合并递归返回的路径列表,彻底消除单独定义newpaths的需求,代码更简洁且从根源避免错误。

运行修复后的代码,会输出正确路径:[['b', 'a', 'c', 'd', 'e'], ['b', 'd', 'e']]

内容的提问来源于stack exchange,提问作者SumSum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 23:05:29