【问题标题】:endless while loop confusion [closed]无尽的while循环混乱[关闭]
【发布时间】:2013-03-18 10:51:39
【问题描述】:

所以我试图在 9x9 网格上规划一条路径,因此 boardSize 为 9。while 循环应该停止路径列表的长度为 81 或更多,那么为什么它有可能达到 3531 的长度时生物在 7,5,目标在 5,2,海拔是 0?我的 while 循环是错误的还是你认为它可能在其他地方?

def planPath(self, creature, goal, board):
        print("in the path")      
        path = [board[creature.x][creature.y]]       
        while goal not in path or len(path) < self.boardSize ** 2:
            print("path length")
            print(len(path))
            nextPossible = {}
            for neighbor in path[-1].neighbors:
                if type(neighbor) is not Land.Water:
                    nextPossible[neighbor] = abs(neighbor.location[0] - goal.location[0]) + abs(neighbor.location[1] - goal.location[1]) + abs(neighbor.elevation - goal.elevation)      
            path.append(min(nextPossible, key=nextPossible.get))
        return path

【问题讨论】:

  • 我认为您只需在您的while 语句中将or 更改为and
  • sign 我担心会是那样的愚蠢,谢谢。
  • @Marius -- 为什么不作为答案发布?有结束的问题比没有的问题好:)
  • @mgilson:是的,抱歉,我不喜欢发布我没有测试过的答案,但我意识到有一堆 cmet 没有回答的问题并不理想。

标签: python while-loop infinite-loop


【解决方案1】:

您希望 while 循环在路径长度达到棋盘上的方格数时结束 - 在您的 while 循环中使用 and 而不是 or 它将在以下任一表达式结束时结束:

goal not in path

或者这个表达式:

len(path) < self.boardSize ** 2

计算为False。使用or,只要其中一个表达式为真,循环就会继续运行。所以你的固定代码是:

def planPath(self, creature, goal, board):
        print("in the path")      
        path = [board[creature.x][creature.y]]       
        while goal not in path and len(path) < self.boardSize ** 2:
            print("path length")
            print(len(path))
            nextPossible = {}
            for neighbor in path[-1].neighbors:
                if type(neighbor) is not Land.Water:
                    nextPossible[neighbor] = abs(neighbor.location[0] - goal.location[0]) + abs(neighbor.location[1] - goal.location[1]) + abs(neighbor.elevation - goal.elevation)      
            path.append(min(nextPossible, key=nextPossible.get))
        return path

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 2019-04-24
    相关资源
    最近更新 更多