简体   繁体   English

如何在Python中递归实现方法

[英]How to implement a method recursively in Python

I am trying to implement this method recursively. 我试图递归地实现此方法。 However, after a few seconds I get an Index Error sayings "Can't pop from empty stack." 但是,几秒钟后,我收到一个“索引错误”消息,说“无法从空堆栈弹出”。 How can I correct this? 我该如何纠正? Essentially, the point of the entire code (which I have not included) is to create a maze and guide a robot through it. 本质上,整个代码(我没有包括)的重点是创建一个迷宫并引导机器人通过它。

empty (unexplored) cell 空(未开发)单元格
EMPTY = 0

cell with an obstacle 有障碍的牢房
OBSTACLE = 1

cell that is on the path 路径上的单元格
ON_PATH = 2

cell that has been explored, but is not on the path 已探索但未在路径上的单元
EXPLORED = 3

cell the robot is in 机器人所在的单元格
ROBOT = 4

def solve(self, location):  

    eventType, done = None, False
    self.maze[location[0]][location[1]] = ROBOT  
    if self.mode == GRAPHICAL_FULL:  
        self.display_init()  
        self.draw_maze()  
    elif self.mode == GRAPHICAL_LIMITED:  
        self.display_init()  
        self.update_maze()  
    while eventType != QUIT and not done:  
        if self.mode == GRAPHICAL_FULL or self.mode == GRAPHICAL_LIMITED:  
            for event in pygame.event.get():  
                eventType = event.type
        new_location = self.find_next_step() 
        if new_location is None:  
            # Mark the current location as a dead end  
            self.maze[location[0]][location[1]] = EXPLORED  
            # pop the next cell off the path stack (go back one space)  
            location = self.path.pop()
            self.maze[location[0]][location[1]] = ROBOT
            self.solve(location)   
        else:  
            self.maze[location[0]][location[1]] = ON_PATH  
            self.path.push(location)  
            location = new_location
            self.solve(location)
        if self.mode == GRAPHICAL_FULL or self.mode == GRAPHICAL_LIMITED:  
            self.clock.tick(self.framerate)  
            self.update_maze()  
            self.screen.blit(self.background, (0,0))  
            pygame.display.flip()  
        if (self.maze[0][0] == EXPLORED or
            location == (self.dimension['x']-1, self.dimension['y']-1)):  
            self.path.push(location)  
            done = True
    return self.path


def find_next_step(self):  
    # Search for a place to go  
    for direction in SEARCH_ORDER:  
        new_location = (self.location[0] + direction['x'],  
                        self.location[1] + direction['y'])  
        if (0 <= new_location[0] < self.dimension['x'] and
            0 <= new_location[1] < self.dimension['y'] and
            self.maze[new_location[0]][new_location[1]] == EMPTY):  
            self.maze[new_location[0]][new_location[1]] = ROBOT  
            return new_location  
    return None

As pop is only called if new_location is None, self.find_next_step() has returned none. 由于仅当new_location为None时才调用pop,因此self.find_next_step()未返回任何值。 Without the code for find_next_step(), its hard to be certain, but my guess is that the robot has traversed all paths, is back at the start (with an empty path), and thus .pop() fails. 如果没有find_next_step()的代码,很难确定,但是我的猜测是机器人已经遍历了所有路径,又回到了起点(空路径),因此.pop()失败了。

Anyway, I'd suggest the error really occurs in the return value from find_next_step(). 无论如何,我建议错误实际上发生在find_next_step()的返回值中。

This isn't really an answer, but I don't have the rep to comment yet, hope this helps ;) 这不是一个真正的答案,但是我还没有评论的人,希望这会有所帮助;)

Update: 更新:

Well, I now have more information, but I still feel a long way from grasping your whole picture. 好了,我现在有了更多信息,但是要掌握您的整个照片,我还有很长的路要走。

However, it appears that find_next_step will return None if there are no empty values of direction in SEARCH_ORDER . 然而,似乎find_next_step将返回None ,如果有没有空值directionSEARCH_ORDER (although I don't know what direction looks like. SEARCH_ORDER is presumably a constant? (Not a big python user)). (尽管我不知道方向是什么SEARCH_ORDER大概是一个常数?(不是Python的大用户))。

Anyway, that will presumably be the case when the robot has explored or otherwise identified all the cells that find_next_step looks at. 无论如何,大概是机器人探查或以其他方式标识了find_next_step查看的所有单元格的情况。

There isn't enough of the application for this to be definitive, but I think your problem is at the end of the pattern. 没有足够的应用程序来确定这一点,但是我认为您的问题就在模式的结尾。 When you move into the final location, you call solve() again. 当您移至最终位置时,再次调用resolve()。 On this loop, you'll get new_location is None and start moving back until you get to the first location, and you get the error because you can't pop anymore locations from your path. 在此循环中,您将获得new_location为None并开始向后移动,直到到达第一个位置为止,并且由于无法再从路径弹出位置而出现错误。 Your check to break the recursion loop doesn't get called until after everything unwinds. 直到一切解散后,才能调用中断递归循环的检查。

Move your check for "done" in something like this... 像这样将您的“完成”支票移走...

location = new_location
if not done:
    self.solve(location)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM