循环混乱的无尽

时间:2013-03-28 04:40:46

标签: python while-loop infinite-loop

所以我试图在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

1 个答案:

答案 0 :(得分:2)

当路径长度达到电路板上的方块数时,您希望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