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

Python UCS实现报AttributeError: 'Node'无'is_goal'属性问题排查

UCS算法AttributeError: 'Node' object has no attribute 'is_goal' 报错解决

触发原因

  1. 核心错误:代码中使用current_node.is_goal访问节点属性,但你使用的Node类没有定义is_goal这个实例属性。通常这类搜索框架的目标节点判断有两种常规实现:要么Node类提供is_goal()实例方法需要加括号调用,要么通过Problem类的is_goal(node)方法判断,不能直接访问属性。
  2. 代码同时存在其他会导致运行异常的问题:
    • UCS类缩进错误,嵌套在get_solver_mapping函数内部,外部无法正常调用
    • 子节点遍历逻辑缩进错误,判断子节点是否访问、入队的代码写在for循环外,只会处理最后一个子节点
    • 入队时使用的current_node_priority变量未定义
    • 导入了题目要求的自定义PriorityQueue,但实际使用了Python标准库的queue.PriorityQueue,不符合接口要求

修复方案

修复后完整代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:15:04