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