How to fill a 3x3 grid to be a valid Sudoku grid in Python

1 Answer

0 votes
import random

# To fill a 3x3 grid to be a valid Sudoku grid, you must ensure that each row, 
# column, and the 3x3 grid contains the numbers 1 through 9 without repetition.

def fill_sudoku_grid():
    # Create a list with numbers 1 to 9
    numbers = list(range(1, 10))

    # Shuffle the numbers randomly
    random.shuffle(numbers)

    # Fill the 3x3 grid row by row
    grid = [[0] * 3 for _ in range(3)]
    index = 0
    for i in range(3):
        for j in range(3):
            grid[i][j] = numbers[index]
            index += 1
    return grid

def print_grid(grid):
    for row in grid:
        print(" ".join(map(str, row)))

# Initialize and fill the 3x3 grid
grid = fill_sudoku_grid()

# Print the grid
print("Generated 3x3 Sudoku Grid:")
print_grid(grid)

 
 
'''
run:
  
Generated 3x3 Sudoku Grid:
6 2 8
4 3 7
5 9 1
  
'''

 



answered Jun 1, 2025 by avibootz

Related questions

...