gpt4 book ai didi

python - python 中奇怪的递归行为

转载 作者:行者123 更新时间:2023-11-28 22:02:18 25 4
gpt4 key购买 nike

我的数独解算器完全按照它应该做的去做 - 除了返回正确的东西。它在返回(正确求解的网格)之前打印它应该打印的内容,但随后它似乎继续运行了一段时间并返回 None。我不知道发生了什么。

网格是列表的列表。假设如果网格有效(已解决或未解决),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,但从未返回其值。

关于python - python 中奇怪的递归行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11486358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com