这是我的密码,它断了线:
if (suc not in sFrontier) or (suc not in sExplored):
给出错误:type error:“instance”类型的参数不可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 []
getSuccessors返回一个继承状态列表、它们需要的操作以及1的开销。
所以之后
lSuccessors = problem.getSuccessors(leaf)
lSuccessors打印
[((5,4), 'South', 1), ((4,5), 'West', 1)]
之后
for suc in lSuccessors:
suc打印
((5,4), 'South', 1)
为什么会坏?是不是因为前额和六边形都是一堆,它看不到一堆?
我需要contain()方法还是只使用list?
感谢所有帮助:)
如果堆栈不支持包含测试,它确实会抛出错误。您需要向它们添加一个^{} method 来支持
in
测试。还有其他方法可以让} expression documentation 。
in
测试在堆栈中找到项,但不建议使用它们,因为它们比__contains__
方法效率低;请参阅^{我假设
util.Stack
是您的类。提供一个
__contains__(self, x)
方法,使对象支持a in obj
检查。查看文档:Emulating container types
SFrontier
是一个包含列表的类。你在代码中检查suc是否在sFrontier类中,因为sFrontier是不可接受的,所以你不能检查它。你必须写(suc in sFrontier.list)
,这样你就可以检查suc是否在你的类sFrontier包含的列表中。相关问题 更多 >
编程相关推荐