这是我在这里的第一篇帖子,我是一个Python初学者,正在为学校项目工作。
我的具体问题是伯克利吃豆人项目1的一部分: https://inst.eecs.berkeley.edu/~cs188/sp19/project1.html
在BFS部分我遇到了麻烦。特别是在tinyMap上,当我的程序处于2,2状态时,它正常过渡到2,3,但2,1有一个额外的北方向。
successorsVisited是一个坐标状态的集合,myQueue是一个普通队列,problem是棋盘,getSuccessors返回一个元组列表(状态,方向,成本),我在将其推回队列之前将其编辑为(状态,方向,成本,路径)。
请假设我已经正确处理了基本情况,这是从队列中开始的5,4和4,5的迭代步骤。
def BFS_Helper(problem,myQueue,successorsVisited): while not myQueue.isEmpty(): node = myQueue.pop() state = node[0] for x in range(0,len(problem.getSuccessors(state))): aTuple = problem.getSuccessors(state)[x] if aTuple[0] not in successorsVisited: successorsVisited.add(aTuple[0]) node[3].append(aTuple[1]) bTuple = (aTuple[0], aTuple[1], aTuple[2], node[3]) # new bTuple with path = path + action print(bTuple) if problem.isGoalState(aTuple[0]): return bTuple[3] myQueue.push(bTuple) return BFS_Helper(problem, myQueue,successorsVisited)
我在检查目标状态之前打印出bTuple,以下是打印输出。加粗的北方向是我的问题,我无法弄清楚它是如何发生的。
((5, 3), ‘South’, 1, [‘South’, ‘South’])
((3, 5), ‘West’, 1, [‘West’, ‘West’])
((4, 3), ‘West’, 1, [‘South’, ‘South’, ‘West’])
((2, 5), ‘West’, 1, [‘West’, ‘West’, ‘West’])
((4, 2), ‘South’, 1, [‘South’, ‘South’, ‘West’, ‘South’])
((1, 5), ‘West’, 1, [‘West’, ‘West’, ‘West’, ‘West’])
((3, 2), ‘West’, 1, [‘South’, ‘South’, ‘West’, ‘South’, ‘West’])
((1, 4), ‘South’, 1, [‘West’, ‘West’, ‘West’, ‘West’, ‘South’])
((2, 2), ‘West’, 1, [‘South’, ‘South’, ‘West’, ‘South’, ‘West’, ‘West’])
((1, 3), ‘South’, 1, [‘West’, ‘West’, ‘West’, ‘West’, ‘South’, ‘South’])
((2, 3), ‘North’, 1, [‘South’, ‘South’, ‘West’, ‘South’, ‘West’, ‘West’, ‘North’])
((2, 1), ‘South’, 1, [‘South’, ‘South’, ‘West’, ‘South’, ‘West’, ‘West’, ‘North’, ‘South’])
((1, 1), ‘West’, 1, [‘South’, ‘South’, ‘West’, ‘South’, ‘West’, ‘West’, ‘North’, ‘South’, ‘West’])
非常感谢您的任何帮助。
回答:
您的问题原因在这里:
node[3].append(aTuple[1])
当循环遍历后续状态的迭代次数增加时,这将成为一个问题。在这些迭代中,使用的是同一个 node[3]
… 它仍然包含来自先前迭代的附加值,您又向其中添加了另一个值。
解决方案:不要修改 node[3]
。相反,动态创建一个新列表:
bTuple = (aTuple[0], aTuple[1], aTuple[2], node[3] + [aTuple[1]])