AttributeError:“int”对象在尝试为深度受限搜索编写递归算法时没有属性“map”

2024-05-23 18:01:25 发布

您现在位置:Python中文网/ 问答频道 /正文

试图为一个6字谜游戏编写一个深度受限搜索的递归算法,但由于某种原因,我一直得到上面的错误,无法理解为什么。 这是我的递归深度有限搜索代码:

def rec_dls(node, limit):
    global cutoff_occurred
    cutoff = 0
    failure = -1
    if goal_state == node.state:
        return node
    elif limit == 0:
        return cutoff          # cutoff
    else:
        cutoff_occurred = False
        actions = moves(node.state) # all possibles children of this state
        for action in actions:
            child = State(action, node, node.depth+1, node.cost+1)
            result = rec_dls(child, limit - 1)
            if result == cutoff:
                cutoff_occurred = True
            elif result != failure:
                return result
        if cutoff_occurred:
            return cutoff
        else:
            return failure
        

def dls(limit):
    node = State(initial_state, None, 0, 0)
    return rec_dls(node, limit)

还有国家级:


class State: 
    def __init__(self, state, parent, depth, cost): 
        self.state = state 
        self.parent = parent 
        self.depth = depth 
        self.cost = cost 
        if self.state: 
            self.map = ''.join(str(e) for e in self.state) 
            
    def __eq__(self, other): 
        return self.map == other.map 
    def __lt__(self, other): 
        return self.map < other.map

这是我在更多细节中遇到的错误:

enter image description here

作为参考,我的工作逻辑基于此(来自“人工智能,现代方法”):

enter image description here


Tags: selfnodemapreturnifdefresultcutoff
1条回答
网友
1楼 · 发布于 2024-05-23 18:01:25

问题不在于rec_dls何时返回int。当它返回一个State对象时

考虑下面的代码行:

           result = rec_dls(child, limit - 1)
           if result == cutoff:
               # ...

假设rec_dls在这里返回一个State对象。然后将State对象与cutoff进行比较,后者包含int0,并且由于您重写了State类中的__eq__,因此此比较导致调用State.__eq__,而other设置为0

作为int0没有map属性,因此您的错误

也许您想在__eq__方法中包含一个检查other是否是另一个State对象:

    def __eq__(self, other): 
        return isinstance(other, State) and self.map == other.map 

相关问题 更多 >