如何在 returns None 的函数中使用变量?

How to use a variable in a function that returns None?

我有下面这个函数,是用来解一个数独格子的。我如何更改代码,使其 returns 求解矩阵,以便我可以将其用于其他用途,而不仅仅是打印它?该函数基本上使用递归来尝试数独网格的所有可能解决方案,如果它属于某个位置,则填充一个数字。来源:https://www.youtube.com/watch?v=G_UYXzGuqvM&t=455s

matrix = np.array([[9,0,7,   1,0,0,   0,0,0],
                   [0,0,0,   0,0,0,   0,0,0],
                   [5,0,0,   3,0,0,   0,6,9],

                   [0,0,1,   6,5,0,   8,0,0],
                   [0,3,0,   0,8,0,   0,4,0],
                   [0,0,6,   0,3,9,   1,0,0],

                   [4,2,0,   0,0,6,   0,0,8],
                   [0,0,0,   0,0,0,   0,0,0],
                   [0,0,0,   0,0,2,   5,0,7]])

def grid(i,j): # function which splits the matrix up into 9 grids
    if i < 3 and j < 3:
        return matrix[0:3,0:3]
    elif  i < 3 and 3 <= j < 6 :
        return matrix[0:3,3:6]
    elif  i < 3 and 6 <= j < 9 :
        return matrix[0:3,6:9]
    elif  3 <= i < 6 and j < 3 :
        return matrix[3:6,0:3]
    elif  3 <= i < 6 and 3 <= j < 6 :
        return matrix[3:6,3:6]
    elif  3 <= i < 6 and 6 <= j < 9:
        return matrix[3:6,6:9]
    elif  6 <= i < 9 and j < 3 :
        return matrix[6:9,0:3]
    elif  6 <= i < 9 and 3 <= j < 6 :
        return matrix[6:9,3:6]
    elif  6 <= i < 9 and 6 <= j < 9 :
        return matrix[6:9,6:9] #

def possible(i,j,n): # function which tells us if a number is possible in a certain position
    if all(matrix[i][m] != n and matrix[m][j] != n for m in range(9)) and n not in grid(i,j):
        return True
    else:
        return False

def solve(): # function which solves the puzzle and fills in correct digits
    global matrix
    for i in range(9):
        for j in range(9):
            if matrix[i][j] == 0:
                for n in range(1,10):
                    if possible(i,j,n):
                        matrix[i][j] = n
                        solve()
                        matrix[i][j] = 0
                return
    print(matrix)


solve()

我尝试使用 return matrix 但这只是 returns 原始矩阵

您的代码存在的问题是您正在处理全局矩阵。在递归调用的深处,您找到了解决方案(并打印出来),但是当返回堆栈时,您将所有字段重置为 0。(参见 chepner 的评论。)

鉴于您正在 "procedural style" 中编码,为什么不使用第二个全局变量(solution 说)并分配一个深层副本。

from copy import deepcopy

...


solution = deepcopy(matrix)

当然,您也可以以更实用的方式重构代码。