我在尝试为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
这是我遇到的错误的更多细节:
作为参考,我的工作逻辑基于《人工智能:现代方法》这本书:
回答:
问题不是当rec_dls返回一个int时发生的。而是当它返回你的State对象时发生的。
考虑以下代码行:
result = rec_dls(child, limit - 1) if result == cutoff: # ...
假设rec_dls在这里返回你的State对象。然后你将你的State对象与cutoff进行比较,cutoff包含int值0,因为你在State类中重写了__eq__,这个比较会导致State.__eq__被调用,other被设置为0。
作为一个int,0没有map属性,因此出现了你的错误。
或许你应该在你的__eq__方法中添加一个检查,确保other是另一个State对象:
def __eq__(self, other): return isinstance(other, State) and self.map == other.map

