【发布时间】:2021-02-21 15:26:19
【问题描述】:
我一直在做数独求解器,遇到了一个问题。
grid = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
]
我在全局范围内有这个网格,并且在同一范围内有这个函数:
def solve_sudoku():
global grid
grid = solver.solve(grid)
这个函数调用solver.py里面的solve函数(我已经把它导入这个脚本了)。
def solve(grid):
# I do all calculations and solve it here and return grid.
return grid
当我在solver.solve函数中打印我的网格时,它会打印解决方案,但是当我将它返回到我的主脚本中的solve_sudoku函数时,网格保持不变。没有任何变化。
这可能是关于传递参数的一个小错误,我在互联网上搜索并无法做到。提前感谢您的帮助..
编辑:
这是我的代码和控制台输出。 (这里省略了代码中不相关的部分)
求解器.py
# Solving algorithm
def solve(grid):
# Scanning grid for empty square.
for y in range(9):
for x in range(9):
if grid[y][x] == 0:
for i in range(1, 10):
if isPossible(y, x, i, grid): #isPossible checks if that number can put on grid, position (x,y)
grid[y][x] = i
solve(grid)
grid[y][x] = 0
return grid
print("The result print: ")
print_grid(grid)
return grid
# I use this function to print my grid into console
def print_grid(grid):
for i in range(9):
if(i % 3 == 0 and i != 0):
print("- - - - - - - - - - - -")
for j in range(9):
if j % 3 == 0 and j != 0:
print(" | ", end="")
if j == 8:
print(str(grid[i][j]))
else:
print(str(grid[i][j]) + " ", end="")
print('\n')
gui.py
grid = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
]
def solve_sudoku():
global grid
print("before: ")
solver.print_grid(grid)
grid = solver.solve(grid)
print("after: ")
solver.print_grid(grid)
def main():
while run_program:
# I do some pygame event check here
# This is the part where I call solve_sudoku function
if mouse_clicked:
if 200 <= xmouse <= 320 and 550 <= ymouse <= 610:
solve_sudoku()
if __name__ == "__main__":
main()
这是输出:(基本上网格在solver.py中发生变化,但在gui.py中保持不变)
之前:
7 8 0 | 4 0 0 | 1 2 0
6 0 0 | 0 7 5 | 0 0 9
0 0 0 | 6 0 1 | 0 7 8
0 0 7 | 0 4 0 | 2 6 0
0 0 1 | 0 5 0 | 9 3 0
9 0 4 | 0 6 0 | 0 0 5
0 7 0 | 3 0 0 | 0 1 2
1 2 0 | 0 0 7 | 4 0 0
0 4 9 | 2 0 6 | 0 0 7
结果打印:
7 8 5 | 4 3 9 | 1 2 6
6 1 2 | 8 7 5 | 3 4 9
4 9 3 | 6 2 1 | 5 7 8
8 5 7 | 9 4 3 | 2 6 1
2 6 1 | 7 5 8 | 9 3 4
9 3 4 | 1 6 2 | 7 8 5
5 7 8 | 3 9 4 | 6 1 2
1 2 6 | 5 8 7 | 4 9 3
3 4 9 | 2 1 6 | 8 5 7
之后:
7 8 0 | 4 0 0 | 1 2 0
6 0 0 | 0 7 5 | 0 0 9
0 0 0 | 6 0 1 | 0 7 8
0 0 7 | 0 4 0 | 2 6 0
0 0 1 | 0 5 0 | 9 3 0
9 0 4 | 0 6 0 | 0 0 5
0 7 0 | 3 0 0 | 0 1 2
1 2 0 | 0 0 7 | 4 0 0
0 4 9 | 2 0 6 | 0 0 7
【问题讨论】:
-
我认为将
grid作为参数传递给solve_sudoku会更简单,执行您的操作并再次返回grid值,然后在外部范围内替换它 -
我完全同意@Anonymous,但如果你仍然想这样做:你的代码对我有用,grid 在solve_sudoku() 中被修改。也许你可以展示更多的代码,以及你正在做的打印(以及在哪里)?