【问题标题】:Python BreathFirstSearch -pathing problemPython BreathFirstSearch - 路径问题
【发布时间】:2020-02-18 18:22:21
【问题描述】:

这是我在这里的第一篇文章,我是一名 Python 初学者,正在为学校项目工作。

我的具体问题是 berkeley pacman project1 的一部分:https://inst.eecs.berkeley.edu/~cs188/sp19/project1.html

在 BFS 部分我遇到了麻烦。特别是在 tinyMap 上,当我的程序处于 2,2 状态时,它通常会转换为 2,3,但 2,1 有一个额外的北方向。

successorsVisited 是一组坐标状态 myQueue 是一个常规队列 问题是董事会 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), '南', 1, ['南', '南'])

((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', '南'])

((1, 1), 'West', 1, ['South', 'South', 'West', 'South', 'West', 'West', 'North', 'South', '西'])

非常感谢您的帮助。

【问题讨论】:

    标签: python artificial-intelligence


    【解决方案1】:

    问题的原因在这里:

    node[3].append(aTuple[1])
    

    当后继循环的迭代次数更多时,这将成为一个问题。在那些迭代中,same node[3] 被使用...它仍然具有前一次迭代的附加值,并且您向其添加 另一个 值。

    解决方案:不要改变node[3]。相反,动态创建一个新列表:

    bTuple = (aTuple[0], aTuple[1], aTuple[2],  node[3] + [aTuple[1]])
    

    【讨论】:

    • 非常感谢!运算符重载是否总是在 python 中生成一个新的非变异变量?在搜索自己时,我一直发现 python 并没有真正的引用或值。
    • 根据经验,在 Python 中,返回结果的方法不会改变操作数(如copy+)。 返回结果的方法或运算符(但None)将改变操作数(如appendextendsort+=...)。这与按引用或按值调用无关。这个概念是关于函数如何处理它们的参数的。在 Python 中没有按引用调用:当您为函数参数分配一个新值时,调用者的变量不受影响。
    猜你喜欢
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 2014-05-09
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 2013-10-01
    相关资源
    最近更新 更多