简体   繁体   English

python中的奇怪递归行为

[英]Strange recursion behaviour in python

My sudoku solver does exactly what it's supposed to do - except returning the correct thing. 我的数独解算器完全执行了应该做的事情-除了返回正确的东西。 It prints what it should right before the return (a correctly solved grid), but then it seems to keep running for a bit and returns None. 它会在返回之前打印正确的内容(正确解决的网格),但是随后似乎会继续运行并返回None。 I can't figure out what's going on. 我不知道发生了什么事。

Grid is a list of lists. 网格是列表的列表。 Assume that check_sudoku returns True if the grid is valid (solved or not), and False otherwise. 假设check_sudoku如果网格有效(已解决或无效),则返回True,否则返回False。

def solve_sudoku(grid, row=0, col=0):
    "Searches for valid numbers to put in blank cells until puzzle is solved."
    # Sanity check
    if not check_sudoku(grid): 
        return None
    # Sudoku is solved
    if row > 8: 
        return grid
    # not a blank, try next cell
    elif grid[row][col] != 0:
        next_cell(grid, row, col)
    else:
        # try every number from 1-9 for current cell until one is valid
        for n in range(1, 10):
            grid[row][col] = n
            if check_sudoku(grid):
                next_cell(grid, row, col)
        else:
            # Sudoku is unsolvable at this point, clear cell and backtrack
            grid[row][col] = 0
            return

def next_cell(grid, row, col):
    "Increments column if column is < 8 otherwise increments row"
    return solve_sudoku(grid, row, col+1) if col < 8 else solve_sudoku(grid, row+1, 0)

您在递归中调用next_cell ,但是从不返回其值。

It seems to me like this will never actually return something useful. 在我看来,这实际上将永远不会返回有用的东西。 The first time we enter your solve_sudoku , you check to see if the grid is solved, and if so you return it. 我们第一次输入您的solve_sudoku ,请检查网格是否已求解,如果是,则将其返回。 After that, you begin a bunch of recursion which ultimately will end up coming back out towards the end of the function and returning None. 之后,您将开始一堆递归,最终将最终返回到函数末尾并返回None。 No matter what, you are returning None all the time. 无论如何,您一直都没有返回。 The only thing that you end up with is a modified grid argument that you passed in to start. 最终唯一要做的就是传递过来的修改后的grid参数。

def solve_sudoku(grid, row=0, col=0):
    # possible return at the first entry point
    if not check_sudoku(grid): 
        return None

    # only time you would ever NOT get None
    if row > 8: 
        return grid

    ...recurse...

    # come back out when the stack unwinds,
    # and there is no return value other than None

What I speculate is happening, is that you are printing the values along the way, and you do properly see a solved grid at the moment it happens, but your function isn't set up to properly completely break out when that is done. 我推测正在发生的事情是,您一直在打印这些值,并且在发生问题时可以正确看到已解决的网格,但是完成此操作后,您的功能并未设置为完全完全中断。 It continues to loop around until it exhausts some range and you see a bunch of extra work. 它继续循环,直到耗尽一定范围,您会看到大量额外的工作。

The important thing to do is to check the return value of the recursive call. 重要的事情是检查递归调用的返回值。 You would either return None if its not solved, or grid if it is. 如果未解决,则返回None;否则,返回grid As it stands, you never care about the result of your recursions in the calling scope. 就目前而言,您永远不必关心调用范围中的递归结果。

Because I don't have all the details about your specific code, here is a simple equivalent: 因为我没有您特定代码的所有详细信息,所以这里有一个简单的等效项:

def solver(aList):
    if aList[0] == 10:
        print "SOLVED!"
        return None

    print "NOT SOLVED..."
    return next(aList)

def next(aList):
    # do some stuff
    # check some stuff
    aList[0] += 1
    return solver(aList)


if __name__ == "__main__":
    data = [0]
    solver(data)
    print data

Notice that the indirectly recursive call to checker() -> solver() has its value returned all the way up the chain. 注意,对checker() -> solver()的间接递归调用在整个链中一直返回其值。 In this case we are saying None means solved, and otherwise it should keep recursing. 在这种情况下,我们说“ None表示已解决,否则应继续递归。 You know that at some point deep in your recursion stack, the solution will be solved. 您知道在递归堆栈的某个深处,解决方案将得到解决。 You will need to communicate that back up to the top right away. 您将需要立即将其传达给顶部。

The communication looks like this: 通讯如下所示:

aList == [0]
solver(aList)
  next(...)
    next(...)
      next(...)
        next(...) 
          #SOLVED
        <- next(...)
      <- next(...)
    <- next(...)
  <- next(...)
<-solver(aList)
aList == [10]

And here is what your version might look like if applied to my simple example: 如果将其应用到我的简单示例中,这就是您的版本:

aList == [0]
solver(aList)
  next(...)
    next(...)
      # SOLVED
      next(...)
        next(...) 
          ...
        <- next(...)
      <- next(...)
    <- next(...)
  <- next(...)
<-solver(aList)
aList == [10]

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

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