【发布时间】:2013-01-13 10:22:36
【问题描述】:
所以这是我的代码,它在该行中断:
if (suc not in sFrontier) or (suc not in sExplored):
给出错误:TypeError: 'instance' 类型的参数不可迭代
"""
The pseudocode I'm following
initialize the frontier using the initial state of the problem
initialize the explored set to be empty
loop do
if the frontier is empty then return failure
choose a leaf node and remove it from the frontier
if the node contains a goal state then return the corresponding solution
add the node to the explored set
expand the chosen node, adding the resulting nodes to the frontier
only if not in the frontier or explored set
"""
sFrontier = util.Stack()
sFrontier.push(problem.getStartState())
sExplored = util.Stack()
lSuccessors = []
while not sFrontier.isEmpty():
leaf = sFrontier.pop()
if problem.isGoalState(leaf):
solution = []
while not sExplored.isEmpty():
solution[:0] = (sExplored.pop())[2]
return solution
sExplored.push(leaf)
lSuccessors = problem.getSuccessors(leaf)
for suc in lSuccessors:
if (suc not in sFrontier) or (suc not in sExplored):
sFrontier.push(suc)
return []
problem.getSuccessors 返回一个后续状态列表、它们需要的操作以及成本 1。
之后
lSuccessors = problem.getSuccessors(leaf)
lSuccessors 打印
[((5,4), 'South', 1), ((4,5), 'West', 1)]
之后
for suc in lSuccessors:
成功打印
((5,4), 'South', 1)
为什么会坏掉?是因为 sFrontier 和 sExplored 是堆栈,它不能在堆栈中查找吗?
我需要一个 contains() 方法还是只使用一个列表来代替?
感谢所有帮助:)
【问题讨论】:
-
该错误有点令人困惑,因为它抱怨您的
Stack对象不可迭代。这样做的原因是,如果您不提供__contains__方法,它会回退到尝试迭代序列或获取其长度并使用__getitem__,并且您会从回退代码中得到错误。所以从技术上讲,它要求您在此处定义__iter__……但您真正想要定义的是__contains__,正如 Martijn Pieters 所说。
标签: python python-2.7 depth-first-search pacman