Sudoku in Python

Python game 11 of 20

Mediumโฑ 45 min๐Ÿ“„ 59 lines of Pythonโ˜… 3 challengesโ–ถ Plays in your browser

Sudoku is a number puzzle: fill a 9ร—9 grid so every row, every column and every 3ร—3 box holds 1 to 9 once. In Python the hard part isn't drawing the grid, it's the rule check, and once you can check a move you are one step away from a solver that cracks any puzzle by itself.

This game makes a fresh puzzle with 12 empty squares. Fill them in, or type hint if you get stuck.

Play Sudoku

sudoku.py ยท real Python in your browser
Press โ–ถ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (59 lines)

How to play

  • Type row, column and number, for example 4 7 2.
  • A number must not repeat in its row, column or 3ร—3 box.
  • Fill every empty square (shown as a dot) to win. Type hint for help.

The complete Sudoku code

Here is the whole program (59 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.

import random

# A valid full grid from a pattern, then shuffled so every game is different.
def full_grid():
    nums = random.sample(range(1, 10), 9)
    rows = [g * 3 + r for g in random.sample(range(3), 3) for r in random.sample(range(3), 3)]
    cols = [g * 3 + c for g in random.sample(range(3), 3) for c in random.sample(range(3), 3)]
    return [[nums[(3 * (r % 3) + r // 3 + c) % 9] for c in cols] for r in rows]


def ok(grid, r, c, n):
    if n in grid[r]:
        return False
    if n in [grid[i][c] for i in range(9)]:
        return False
    br, bc = r // 3 * 3, c // 3 * 3
    return all(grid[y][x] != n for y in range(br, br + 3) for x in range(bc, bc + 3))


def show(grid):
    for r in range(9):
        if r % 3 == 0:
            print("  +-------+-------+-------+")
        row = ""
        for c in range(9):
            row += ("| " if c % 3 == 0 else "") + (str(grid[r][c]) if grid[r][c] else ".") + " "
        print(f"{r + 1} {row}|")
    print("  +-------+-------+-------+")
    print("    1 2 3   4 5 6   7 8 9")


answer = full_grid()
grid = [row[:] for row in answer]
holes = random.sample([(r, c) for r in range(9) for c in range(9)], 12)
for r, c in holes:
    grid[r][c] = 0

print("SUDOKU  -  fill the dots. Type: row column number (or 'hint')")
while any(0 in row for row in grid):
    show(grid)
    text = input("> ").strip().lower()
    if text == "hint":
        r, c = next((r, c) for r, c in holes if grid[r][c] == 0)
        grid[r][c] = answer[r][c]
        print(f"Row {r + 1}, column {c + 1} is {answer[r][c]}.")
        continue
    parts = text.split()
    if len(parts) != 3 or not all(p.isdigit() and 1 <= int(p) <= 9 for p in parts):
        print("Type three numbers from 1 to 9, like: 4 7 2")
        continue
    r, c, n = int(parts[0]) - 1, int(parts[1]) - 1, int(parts[2])
    if (r, c) not in holes:
        print("That square was given at the start.")
    elif not ok(grid, r, c, n) and grid[r][c] != n:
        print(f"{n} is already in that row, column or box.")
    else:
        grid[r][c] = n
show(grid)
print("Solved! Every row, column and box is complete.")

How the Sudoku game works, step by step

01Make a valid grid fast

A neat formula, (3 * (r % 3) + r // 3 + c) % 9, fills a correct Sudoku. Shuffling the digits, the rows inside each band and the columns inside each stack keeps it valid but makes every game look new.

return [[nums[(3 * (r % 3) + r // 3 + c) % 9] for c in cols] for r in rows]

02Check a move against the three rules

Is n already in the row? In the column? In the 3ร—3 box? The box's top-left corner is the row and column rounded down to a multiple of 3: r // 3 * 3.

br, bc = r // 3 * 3, c // 3 * 3
return all(grid[y][x] != n for y in range(br, br + 3) for x in range(bc, bc + 3))

03Copy the grid before punching holes

[row[:] for row in answer] copies each row, so blanking squares in the puzzle doesn't erase the stored answer used for hints.

grid = [row[:] for row in answer]

04Print the boxes

% (remainder) decides where lines go: a divider before rows 0, 3 and 6, and a bar before columns 0, 3 and 6.

if r % 3 == 0:
    print("  +-------+-------+-------+")

05Loop until the grid is full

any(0 in row for row in grid) is True while at least one empty square remains.

while any(0 in row for row in grid):

What you'll learn

  • 2D lists and copying them correctly
  • Integer division // and remainder %
  • any() and all()
  • Validating moves with functions
  • Backtracking (in the challenges)

Python concepts in this game:

Sudoku coding challenges

Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).

1/3

Is a row valid?

Write row_ok(row) for a list of 9 numbers where 0 means empty: return True if no number from 1 to 9 appears twice.

challenge 1 ยท edit, Run, then Check
Hint

Remove the zeros, then compare the length of the list with the length of set(list).

Show a solution
def row_ok(row):
    filled = [n for n in row if n != 0]
    return len(filled) == len(set(filled))

print(row_ok([5, 3, 0, 0, 7, 0, 0, 0, 0]))
2/3

Find the box

Write box(grid, r, c) that returns a list of the 9 numbers in the 3ร—3 box containing square (r, c), reading left to right, top to bottom.

challenge 2 ยท edit, Run, then Check
Hint

The box starts at row r // 3 * 3 and column c // 3 * 3.

Show a solution
def box(grid, r, c):
    br, bc = r // 3 * 3, c // 3 * 3
    return [grid[y][x] for y in range(br, br + 3) for x in range(bc, bc + 3)]

g = [[r * 9 + c for c in range(9)] for r in range(9)]
print(box(g, 4, 7))
3/3

A backtracking solver

Finish solve(grid): find an empty square (0), try 1 to 9 there using the given ok(), call solve again, and undo the number if that fails. Return True when the grid is full.

challenge 3 ยท edit, Run, then Check
Hint

Inside the if: for n in range(1, 10): if ok(...), place it, if solve(grid): return True, else set it back to 0. After the loop, return False.

Show a solution
def ok(grid, r, c, n):
    if n in grid[r] or n in [grid[i][c] for i in range(9)]:
        return False
    br, bc = r // 3 * 3, c // 3 * 3
    return all(grid[y][x] != n for y in range(br, br + 3) for x in range(bc, bc + 3))

def solve(grid):
    for r in range(9):
        for c in range(9):
            if grid[r][c] == 0:
                for n in range(1, 10):
                    if ok(grid, r, c, n):
                        grid[r][c] = n
                        if solve(grid):
                            return True
                        grid[r][c] = 0
                return False
    return True

puzzle = [[5,3,0,0,7,0,0,0,0],[6,0,0,1,9,5,0,0,0],[0,9,8,0,0,0,0,6,0],
          [8,0,0,0,6,0,0,0,3],[4,0,0,8,0,3,0,0,1],[7,0,0,0,2,0,0,0,6],
          [0,6,0,0,0,0,2,8,0],[0,0,0,4,1,9,0,0,5],[0,0,0,0,8,0,0,7,9]]
print(solve(puzzle))
print(puzzle[0])

Make it your own

Once your challenges pass, try one of these upgrades:

  • Let the player choose how many squares to remove.
  • Add pencil marks: small notes of possible numbers.
  • Use the solver to make sure a puzzle has only one answer.
  • Time each game and keep a best time.

Frequently asked questions

How do you check a Sudoku move in Python?

Look for the number in the row (grid[r]), in the column ([grid[i][c] for i in range(9)]) and in the 3x3 box that starts at r // 3 * 3, c // 3 * 3. If it's in none of them, the move is allowed.

How does a Sudoku solver work in Python?

Backtracking: find an empty square, try each number that follows the rules, call the solver again, and undo the number if the rest of the grid can't be finished.

How can a program make new Sudoku puzzles?

Build a valid full grid (this page uses a pattern plus shuffles), then remove squares. For hard puzzles, also check with a solver that only one solution is left.

More games like this