https://github.com/Malaya2184/PY100/blob/master/sudoku/sudoku.ipynb need solution to my program i.e 9*9 sudoku solving prohram in python
Asked
Active
Viewed 52 times
-2
-
What's the problem? It seems to be working. – Mike67 Sep 17 '20 at 00:47
-
But it is not working.. I think there is some mistake in my return statements but i am unable to find out. – spider_Malaya Sep 17 '20 at 05:54
1 Answers
0
I put a full script together from your jupyter blocks. It runs correctly.
Please try this code as a single script.
# 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)
Output
(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
You should switch to an IDE (Pycharm\Spyder\VSCode) for larger scripts. Jupyter is mostly for testing small blocks of code.

Mike67
- 11,175
- 2
- 7
- 15