试图为一个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
这是我在更多细节中遇到的错误:
作为参考,我的工作逻辑基于此(来自“人工智能,现代方法”):
问题不在于
rec_dls
何时返回int
。当它返回一个State
对象时考虑下面的代码行:
假设
rec_dls
在这里返回一个State
对象。然后将State
对象与cutoff
进行比较,后者包含int
值0
,并且由于您重写了State
类中的__eq__
,因此此比较导致调用State.__eq__
,而other
设置为0
作为
int
,0
没有map
属性,因此您的错误也许您想在
__eq__
方法中包含一个检查other
是否是另一个State
对象:相关问题 更多 >
编程相关推荐