### 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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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