python - 卡在数独解决程序中..无法找出我的错误
问题描述
https://github.com/Malaya2184/PY100/blob/master/sudoku/sudoku.ipynb 需要解决我的程序,即 9*9 数独在 python 中解决 prohram
解决方案
我将您的 jupyter 块中的完整脚本放在一起。它运行正确。
请将此代码作为单个脚本尝试。
# printing of the sudoku board to the console
import numpy as np
board = [
[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]
]
# print(np.matrix(board))
# print(len(board))
def print_board(bo):
for i in range(len(bo)):
if i % 3 == 0 and i !=0:
print('- - - - - - - - - - -')
for j in range(len(bo)):
if j % 3 == 0 and j !=0:
print('|', end=" ")
if j == 8:
print(bo[i][j])
else:
print(bo[i][j], end=" ")
def find_empty(bo):
# empty = []
for x in range(len(bo)):
for y in range(len(bo)):
if bo[x][y] == 0:
return (x ,y)
return True
# to see the empty positions in the board
# empty.append([i,j])
# return empty
# print(find_empty(board))
#print(find_empty(board))
def valid(bo, x , y , num):
for i in range(len(bo)):
if bo[x][i] == num:
return False
for i in range(len(bo)):
if bo[i][y] == num:
return False
x0_box = (x//3)*3
y0_box = (y//3)*3
for i in range(0,3):
for j in range(0,3):
if bo[x0_box+i][y0_box+j] == num:
return False
return True
#valid(board, 0, 2, 5 )
def solve(bo):
found = find_empty(bo)
if not found:
return True
else:
x, y = found
for num in range(1,10):
if valid(bo,x, y, num):
bo[x][y] = num
if solve(bo):
return True
bo[x][y]= 0
return
solve(board)
print_board(board)
输出
(0, 2)
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
对于较大的脚本,您应该切换到 IDE (Pycharm\Spyder\VSCode)。Jupyter 主要用于测试小块代码。
推荐阅读
- apache-spark - 有没有可能在不执行的情况下提取火花作业的 DAG 的方法?
- artifactory - 保存 Artifactory 存储的最佳方法
- javascript - 如何知道类的实例是否来自单例?
- python - 如何从 pyspark 数据帧中保存文件,以便稍后访问以将其上传到 S3?
- python - 在 Python 中使用带有 Selenium 的代理
- java - 如何创建注入特定@Repository 的通用@Service?
- amazon-web-services - 如何在 dynamodb 中交换两个表?
- python - sqlalchemy 错误的烧瓶中未显示代码 500 的自定义错误页面
- java - 当用户打开活动但仅在自上次请求以来已过去 24 小时时,我如何发出网络请求?
- html - 我想使图像居中