Python UCS实现报AttributeError: 'Node'无'is_goal'属性问题排查
UCS算法AttributeError: 'Node' object has no attribute 'is_goal' 报错解决
触发原因
- 核心错误:代码中使用
current_node.is_goal访问节点属性,但你使用的Node类没有定义is_goal这个实例属性。通常这类搜索框架的目标节点判断有两种常规实现:要么Node类提供is_goal()实例方法需要加括号调用,要么通过Problem类的is_goal(node)方法判断,不能直接访问属性。 - 代码同时存在其他会导致运行异常的问题:
- UCS类缩进错误,嵌套在
get_solver_mapping函数内部,外部无法正常调用 - 子节点遍历逻辑缩进错误,判断子节点是否访问、入队的代码写在for循环外,只会处理最后一个子节点
- 入队时使用的
current_node_priority变量未定义 - 导入了题目要求的自定义PriorityQueue,但实际使用了Python标准库的queue.PriorityQueue,不符合接口要求
- UCS类缩进错误,嵌套在
修复方案
修复后完整代码
from ..problem import Problem from ..datastructures.priority_queue import PriorityQueue def get_solver_mapping(): return dict(ucs=UCS) class UCS(object): def solve(self, problem: Problem): node = problem.get_start_node() visited = set() # 使用题目要求的自定义优先队列 pq = PriorityQueue() # 按自定义队列接口入队:(优先级, 元素) pq.put(0, (node, [node])) while not pq.empty(): f, (current_node, path) = pq.get() # 已经访问过的节点跳过,避免重复处理 if current_node in visited: continue visited.add(current_node) # 修正目标节点判断,按需二选一: # 方案1:如果Node类提供is_goal方法 # if current_node.is_goal(): # 方案2:如果Problem类提供判断接口(更常用) if problem.is_goal(current_node): return path # 修正缩进,遍历所有子节点 for edge in current_node.out_edges: child = edge.to() if child not in visited: # 用出队的当前优先级f计算新优先级 new_priority = f + edge.weight pq.put(new_priority, (child, path + [child])) return None
关键修改点说明
- 替换了属性访问的错误写法,使用正确的目标节点判断接口
- 修正了所有缩进错误,保证类、循环逻辑作用域正确
- 替换为题目要求的自定义优先队列,适配给定的
put/get接口 - 替换未定义的
current_node_priority为出队拿到的当前节点优先级f - 补充了重复节点判断逻辑,避免同一个节点多次入队导致的冗余计算
内容的提问来源于stack exchange,提问作者ADE
相关产品推荐
相关产品推荐

