Write a Sudoku generator in Python that generates a Sudoku game in the console, then…
- User
Write a Sudoku generator in Python that generates a Sudoku game in the console, then solves it underneath automatically
- Assistant
Write a Sudoku generator in Python that generates a Sudoku game in the console, then solves it underneath automatically
Sure! Below is a Python script that generates a Sudoku puzzle, displays it in the console, and then solves it automatically underneath. The script ensures that the generated puzzle has a unique solution.
import random
import copy
def print_grid(grid):
"""Prints the Sudoku grid in a formatted manner."""
for i in range(9):
row = ""
for j in range(9):
num = grid[i][j]
if num == 0:
row += ". "
else:
row += str(num) + " "
if (j + 1) % 3 == 0 and j < 8:
row += "| "
print(row)
if (i + 1) % 3 == 0 and i < 8:
print("- " * 11)
def find_empty(grid):
"""Finds an empty cell in the grid. Returns (row, col) or None."""
for i in range(9):
for j in range(9):
if grid[i][j] == 0:
return (i, j)
return None
def is_valid(grid, num, pos):
"""Checks whether it's valid to place num at pos in grid."""
row, col = pos
# Check row
if any(grid[row][x] == num for x in range(9)):
return False
# Check column
if any(grid[y][col] == num for y in range(9)):
return False
# Check box
box_x = col // 3
box_y = row // 3
for y in range(box_y*3, box_y*3 + 3):
for x in range(box_x*3, box_x*3 + 3):
if grid[y][x] == num:
return False
return True
def solve(grid, solutions, limit=2):
"""Solves the Sudoku grid using backtracking. Counts number of solutions up to limit."""
empty = find_empty(grid)
if not empty:
solutions.append(copy.deepcopy(grid))
return
row, col = empty
for num in range(1, 10):
if is_valid(grid, num, (row, col)):
grid[row][col] = num
solve(grid, solutions, limit)
if len(solutions) >= limit:
return
grid[row][col] = 0
def generate_full_grid():
"""Generates a complete, valid Sudoku grid."""
grid = [[0 for _ in range(9)] for _ in range(9)]
numbers = list(range(1, 10))
def fill_grid(grid):
empty = find_empty(grid)
if not empty:
return True
row, col = empty
random.shuffle(numbers)
for num in numbers:
if is_valid(grid, num, (row, col)):
grid[row][col] = num
if fill_grid(grid):
return True
grid[row][col] = 0
return False
fill_grid(grid)
return grid
def remove_numbers(grid, difficulty=5):
"""Removes numbers from the grid to create a puzzle.
Difficulty parameter controls the number of cells to remove (higher is harder)."""
attempts = difficulty * 5 # Number of attempts to remove
grid = copy.deepcopy(grid)
while attempts > 0:
row = random.randint(0,8)
col = random.randint(0,8)
while grid[row][col] == 0:
row = random.randint(0,8)
col = random.randint(0,8)
backup = grid[row][col]
grid[row][col] = 0
# Make a copy and attempt to solve
grid_copy = copy.deepcopy(grid)
solutions = []
solve(grid_copy, solutions, limit=2)
if len(solutions) != 1:
grid[row][col] = backup
attempts -=1
return grid
def main():
print("Generating complete Sudoku grid...")
full_grid = generate_full_grid()
print("\nComplete Sudoku Grid:")
print_grid(full_grid)
print("\nGenerating Sudoku puzzle by removing numbers...")
puzzle_grid = remove_numbers(full_grid, difficulty=5)
print("\nSudoku Puzzle:")
print_grid(puzzle_grid)
print("\nSolving the Sudoku puzzle...")
solutions = []
solve(copy.deepcopy(puzzle_grid), solutions)
if solutions:
print("\nSolution:")
print_grid(solutions[0])
else:
print("No solution found.")
if __name__ == "__main__":
main()
Printing the Grid (print_grid):
.).Finding Empty Cells (find_empty):
0).(row, col) or None if the grid is full.Validity Check (is_valid):
Solver (solve):
Full Grid Generation (generate_full_grid):
Puzzle Generation (remove_numbers):
difficulty parameter controls how many numbers are removed (higher means more removals and a harder puzzle).Main Function (main):
Save the Script:
sudoku_generator.py.Run the Script:
Open your terminal or command prompt.
Navigate to the directory containing the script.
Execute the script using Python:
python sudoku_generator.py
Generating complete Sudoku grid...
Complete Sudoku Grid:
5 3 4 |6 7 8 |9 1 2
6 7 2 |1 9 5 |3 4 8
1 9 8 |3 4 2 |5 6 7
- - - - - - - - - - -
8 5 9 |7 6 1 |4 2 3
4 2 6 |8 5 3 |7 9 1
7 1 3 |9 2 4 |8 5 6
- - - - - - - - - - -
9 6 1 |5 3 7 |2 8 4
2 8 7 |4 1 9 |6 3 5
3 4 5 |2 8 6 |1 7 9
Generating Sudoku puzzle by removing numbers...
Sudoku Puzzle:
5 3 . |6 . 8 |9 1 2
6 7 2 |1 9 5 |3 . 8
1 9 8 |3 . 2 |5 6 7
- - - - - - - - - - -
8 . 9 |7 6 1 |4 2 3
4 2 6 |8 5 3 |7 9 1
7 1 3 |9 2 4 |8 . 6
- - - - - - - - - - -
9 6 1 |5 3 7 |2 8 4
2 8 7 |4 1 9 |6 3 5
3 4 5 |2 8 6 |1 7 9
Solving the Sudoku puzzle...
Solution:
5 3 4 |6 7 8 |9 1 2
6 7 2 |1 9 5 |3 4 8
1 9 8 |3 4 2 |5 6 7
- - - - - - - - - - -
8 5 9 |7 6 1 |4 2 3
4 2 6 |8 5 3 |7 9 1
7 1 3 |9 2 4 |8 5 6
- - - - - - - - - - -
9 6 1 |5 3 7 |2 8 4
2 8 7 |4 1 9 |6 3 5
3 4 5 |2 8 6 |1 7 9
Difficulty Parameter: You can adjust the difficulty parameter in the remove_numbers function to make the puzzle easier or harder. A higher value removes more numbers, increasing the puzzle's difficulty.
Unique Solution: The script ensures that the generated puzzle has only one unique solution by attempting to find more than one solution after each removal. If multiple solutions are found, the removal is reverted.
Representation: In the printed grid:
.) represent empty cells.Customization: Feel free to modify the script to adjust the difficulty, change the representation of empty cells, or enhance the user interface.
random and copy), so no additional installations are required.Enjoy your Sudoku generator and solver!
Not yet included in a published release.