I have been trying to write a program that generates a Sudoku puzzle but my program doesn't seem to work. It would seem that the program takes too long to run as my 4X4 is able to generate results. The 2 print statements inserted are indeed printing '1's and '2's.
import random
board = []
for nine in range(9):
board.append([0, 0, 0, 0, 0, 0, 0, 0, 0])
def sudoku():
for index in range(81):
row = index // 9
col = index % 9
while board[row][col] == 0:
chosen = random.randint(1, 9)
print(1)
if chosen not in board[row]:
if check_col(col, chosen) != 1:
if row < 3:
if col < 3:
if check_square(0, 0, chosen) != 1:
board[row][col] = chosen
elif col < 6:
if check_square(0, 3, chosen) != 1:
board[row][col] = chosen
else:
if check_square(0, 6, chosen) != 1:
board[row][col] = chosen
print(2)
elif row < 6:
if col < 3:
if check_square(3, 0, chosen) != 1:
board[row][col] = chosen
elif col < 6:
if check_square(3, 3, chosen) != 1:
board[row][col] = chosen
else:
if check_square(3, 6, chosen) != 1:
board[row][col] = chosen
else:
if col < 3:
if check_square(6, 0, chosen) != 1:
board[row][col] = chosen
elif col < 6:
if check_square(6, 3, chosen) != 1:
board[row][col] = chosen
else:
if check_square(6, 6, chosen) != 1:
board[row][col] = chosen
def check_col(col, chosen):
check = 0
for c_row in range(9):
if chosen == board[c_row][col]:
check = 1
return check
def check_square(starting_row, starting_col, chosen):
check = 0
for c_add in range(3):
if chosen in board[starting_row + c_add][starting_col:starting_col + 3]:
check = 1
return check
sudoku()
for printing in range(9):
print(board[printing])