Thorsten Altenkirch教授的Python Sudoku Solver代码问题

问题描述 投票:0回答:1

我偶然发现了Computerphile的YouTube视频,解释了一个简短有效的Python Sudoku求解器。 https://www.youtube.com/watch?v=G_UYXzGuqvM

这里是代码:

import numpy as np

# Defining the sudoku
grid = [[5,3,0,0,7,0,0,0,0],
        [6,0,0,1,9,5,0,0,0],
        [0,9,8,0,0,0,0,6,0],
        [8,0,0,0,6,0,0,0,3],
        [4,0,0,8,0,3,0,0,1],
        [7,0,0,0,2,0,0,0,6],
        [0,6,0,0,0,0,2,8,0],
        [0,0,0,4,1,9,0,0,5],
        [0,0,0,0,8,0,0,7,9]]

def possible(y,x,n):
    global grid
    for i in range(0,9):
        if grid[y][i] == n:
            return False
    for i in range(0,9):
        if grid[i][x] == n:
            return False
    x0 = (x//3)*3
    y0 = (y//3)*3
    for i in range(0,3):
        for j in range(0,3):
            if grid[y0+i][x0+j] == n:
                return False
    return True

def solve():
    global grid
    for y in range(9):
        for x in range(9):
            if grid[y][x] == 0:
                for n in range(1,10):
                    if possible(y,x,n):
                        grid[x][y] = n
                        solve()
                        grid[x][y] = 0
    print(np.matrix(grid))
    input("More? ") # Attempts to find more solutions. In a good sudoku it should terminate the program

solve()

我在Atom上运行代码的教授正在使用Jupyter。当我一直陷入循环并始终受到运行时错误的打击时,这似乎对他来说非常有效。我无法弄清楚代码中是否有错误,或者在Atom或任何其他文本编辑器上运行代码时是否应该意识到一些差异。请记住,我通过Hydrogen软件包在Atom上具有Jupyter内核,因此我真的看不到在Atom上运行代码与Jupyter有何不同。

谢谢您的帮助。

python solver sudoku
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.