为什么这个函数打印结果,但没有返回?

问题描述

def solve(sudoku):
    for y in range(9):
        for x in range(9):
            if sudoku[y][x] == 0:
                for n in range(1,10): 
                    if possible(x,y,n):
                        sudoku[y][x] = n
                        solve(sudoku)
                        sudoku[y][x] = 0
                        
                return
    print(np.matrix(sudoku))
    return sudoku

函数打印已解决的数独,但 print(solve(sudoku)) 不返回任何值。如果可以打印(数独),为什么该函数不返回任何内容

解决方法



def solve(sudoku):
    for y in range(9):
        for x in range(9):
            if sudoku[y][x] == 0:
                for n in range(1,10): 
                    if possible(x,y,n):
                        sudoku[y][x] = n
                        solve(sudoku)
                        sudoku[y][x] = 0
                        
                return # this might be a problem
    print(np.matrix(sudoku))
    return sudoku

,

你的假设肯定是错误的。

如果您说 print(solve(sudoku)) 打印 None,那么这一定是正在发生的事情。

发生这种情况的唯一方法是最后一个 return 来自代码底部的第三行。