generate a sudoku board in python

Here's a simple implementation of a function to generate a Sudoku board using backtracking in Python:

main.py
import random

def generate_board():
    # Initialize an empty 9x9 grid
    board = [[0 for _ in range(9)] for _ in range(9)]
    
    # Fill the cells of the grid using backtracking
    fill_cell(0, 0, board)
    
    # Remove some cells to create a puzzle
    remove_cells(board)
    
    return board

def fill_cell(row, col, board):
    # Base case: the current cell is out of bounds
    if row == 9:
        return True
    
    # Calculate the next row and column
    next_row, next_col = (row, col+1) if col < 8 else (row+1, 0)
    
    # If the current cell is already filled, move on to the next cell
    if board[row][col] != 0:
        return fill_cell(next_row, next_col, board)
    
    # Generate a list of candidate values for the current cell
    candidates = list(range(1, 10))
    random.shuffle(candidates)
    
    # Try each candidate value in turn
    for val in candidates:
        if is_valid(row, col, val, board):
            board[row][col] = val
            if fill_cell(next_row, next_col, board):
                return True
            board[row][col] = 0
    
    # If none of the candidates work, backtrack
    return False

def is_valid(row, col, val, board):
    # Check for duplicates in row and column
    for i in range(9):
        if board[row][i] == val or board[i][col] == val:
            return False
        
    # Check for duplicates in 3x3 box
    box_row = (row // 3) * 3
    box_col = (col // 3) * 3
    for i in range(3):
        for j in range(3):
            if board[box_row+i][box_col+j] == val:
                return False
    
    # If no duplicates found, cell is valid
    return True

def remove_cells(board):
    # Generate a list of all cell indices
    cells = [(i, j) for i in range(9) for j in range(9)]
    
    # Randomly remove some cells from the board
    for i in range(len(cells) // 2):
        row, col = cells.pop(random.randrange(len(cells)))
        board[row][col] = 0
1946 chars
67 lines

You can then use this function to generate a Sudoku board:

main.py
board = generate_board()
print(board)
38 chars
3 lines

This will output a 9x9 grid representing a randomly generated Sudoku puzzle.

gistlibby LogSnag