Make Sudoku generator using Python

Hello friends! Today we’ll be learning create Sudoku generator using Python. This is simple python code in the tutorial.

Code

import random
def print_board(board):
for row in board:
print(" ".join(map(str, row)))
def is_valid(board, row, col, num):
# Check if the number is not present in the same row and column
if num in board[row] or num in [board[i][col] for i in range(9)]:
return False
# Check if the number is not present in the 3x3 subgrid
start_row, start_col = 3 * (row // 3), 3 * (col // 3)
for i in range(start_row, start_row + 3):
for j in range(start_col, start_col + 3):
if board[i][j] == num:
return False
return True
def solve_sudoku(board):
empty_cell = find_empty_cell(board)
if not empty_cell:
return True  # Board is solved
row, col = empty_cell
for num in range(1, 10):
if is_valid(board, row, col, num):
board[row][col] = num
if solve_sudoku(board):
return True  # Continue with the next empty cell
board[row][col] = 0  # Backtrack if the current placement doesn't lead to a solution
return False  # No valid number for the current empty cell
def find_empty_cell(board):
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return (i, j)
return None
def generate_sudoku():
board = [[0] * 9 for _ in range(9)]
solve_sudoku(board)
# Remove some numbers to create a puzzle
empty_cells = random.sample([(i, j) for i in range(9) for j in range(9)], 40)
for cell in empty_cells:
board[cell[0]][cell[1]] = 0
return board
if __name__ == "__main__":
sudoku_board = generate_sudoku()
print("Generated Sudoku Puzzle:")
print_board(sudoku_board)


Keep visiting Analytics Tuts for more tutorials.

Thanks for reading! Comment your suggestions and queries


Leave a Reply

Your email address will not be published. Required fields are marked *