### AttributeError: 在尝试编写深度受限搜索的递归算法时出现’int’对象没有属性’map’的错误

我在尝试为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)

还有State类:

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


回答:

问题不是当rec_dls返回一个int时发生的。而是当它返回你的State对象时发生的。

考虑以下代码行:

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

假设rec_dls在这里返回你的State对象。然后你将你的State对象与cutoff进行比较,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 

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注