类型错误:'实例'类型的参数不可迭代
这是我的代码,出错的地方在这一行:
if (suc not in sFrontier) or (suc not in sExplored):
出现的错误是:TypeError: argument of type 'instance' is not iterable
"""
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:
suc 打印出来的内容是
((5,4), 'South', 1)
为什么会出错呢?是因为 sFrontier 和 sExplored 是栈,所以无法在栈里查找吗?
我需要一个 contain() 方法,还是直接用列表就可以了?
感谢大家的帮助 :)
4 个回答
1
SFrontier
是一个类,它里面有一个列表。在你的代码中,你在检查 suc
是否在 sFrontier
这个类里,但这样做是不行的,因为 sFrontier
不能被遍历,所以你无法直接检查。你需要写 (suc in sFrontier.list)
,这样才能检查 suc
是否在 sFrontier
这个类所包含的列表里。
2
我猜你说的 util.Stack
是你自己写的类。
你需要提供一个 __contains__(self, x)
方法,这样就可以让你的对象支持像 a in obj
这样的检查。
可以参考一下文档:模拟容器类型
3
如果你的栈不支持包含测试,确实会出现错误。你需要给它们添加一个 __contains__
方法,这样才能支持 in
测试。
还有其他方法可以让 in
测试在你的栈中找到项目,但这些方法不推荐使用,因为它们的效率比 __contains__
方法要差;具体可以查看 in
表达式的文档。