Print 语句在函数中工作,但不在代码主体中工作



Python 初学者在这里

我正在编写一个解决数独的脚本。大部分代码取自此视频。

只要我的 print 语句在函数中,该函数就可以工作并打印已解决的网格,但是当我将其放在函数之外时,它会打印出原始数组而不是已解决的数组。

知道为什么会发生这种情况以及如何在代码正文中的函数之外访问已解决的数组。

你们都可以忽略测试函数,因为它们在从函数打印已解决的数组时工作,我的问题是如何打印它并从正文访问它。

我希望打印语句 3 或 4 是已解决的数组。

任何帮助将不胜感激。

import numpy as np
sudoku_grid = np.array([[4, 0, 0, 0, 0, 1, 6, 3, 7],
[0, 6, 0, 0, 4, 0, 0, 5, 1],
[0, 0, 0, 6, 3, 0, 0, 0, 0],
[0, 2, 0, 0, 0, 8, 1, 0, 0],
[6, 0, 8, 9, 0, 5, 3, 0, 4],
[0, 0, 1, 4, 0, 0, 0, 8, 0],
[0, 0, 0, 0, 9, 3, 0, 0, 0],
[7, 8, 0, 0, 6, 0, 0, 1, 0],
[2, 3, 6, 1, 0, 0, 0, 0, 8]])
def possible(row, column, number, grid):
"""Checks whether a number can be inserted in a cell"""
# Checking for duplicate number in row
for i in range(9):
if number == grid[row, i]:
return False
# Checking for duplicate number in column
for j in range(9):
if number == grid[j, column]:
return False
# Checking for duplicate number in grid
# Returns 0,1,2 for row and column so basically 9X9 grid is reduced to 3X3 grid         
and duplicated are checked within the same
r = row//3*3
c = column//3*3
for k in range(r, r+3):
for l in range(c, c+3):
if number == grid[k, l]:
return False
return True

def solve(grid):
"""Solves sudoku using recursion and back tracking"""
# use combination of row and column to get a cell
for i in range(9):
for j in range(9):
# if cell is zero then tries to enter number
if grid[i, j] == 0:
for k in range(1, 10):
# Checks if number is possible and enters the same in array
if possible(i, j, k, grid):
grid[i, j] = k
# Recursion moves to next cell
solve(grid)
# Backtracks if not possible
grid[i, j] = 0
# if no numbers are 0 then Solved and return array
return grid
print(grid, "n Print statement 2(function print statement)")

print(sudoku_grid, "n Print statement 1(Original grid b/f function)")
print("________________________")
x = solve(sudoku_grid)
print("________________________")
print(x, "n Print statement 3")
print("________________________")
print(sudoku_grid, "n Print statement 4")

根据你的函数solve,你的代码要么:

  • 返回网格,或
  • 打印网格

请注意,return发生在for周期内,打印发生在它之后。如果函数已返回,则不会发生打印。

你永远不会到达这部分代码:

# if no numbers are 0 then Solved and return array
return grid

那是因为你是在无条件的情况下进行递归:

# Recursion moves to next cell
solve(grid)

请注意

# if cell is zero then tries to enter number
if grid[i, j] == 0:
for k in range(1, 10):
...
solve(grid)
...
# if no numbers are 0 then Solved and return array
return grid

本身是不连贯的,因为您正在输入一个存在 0 单元格的条件,但是如果没有一个是 0,您期望返回......即使发生这种情况,语句的顺序也不会允许返回网格,因为对solve的调用是在 return 语句之前完成的。

因此,您必须有一个条件,该条件将使您不调用solve而是返回网格 - 两者在相同的范围/条件中将不起作用。

最新更新