Paul's Python CoursePPC

Project 13 of 15, for Caitlin

Sudoku Solver

A sudoku solver for Caitlin's puzzle book: fill a square, check it, and back out of every dead end, until the puzzle is solved or shown to be impossible.

About an hour and a half, in 7 steps.

Sign up free to open itLog in

Act 4 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • CaitlinThese are the last three sudokus in my puzzle book, and there are no answers in the back.
  • CaitlinTwo of them took me under ten minutes each, but I've been stuck on the third for a week.
  • CaitlinEither I'm wrong or the puzzle is, and I'd like to know which, quickly.
  • PaulHave it try everything carefully and back out of every dead end, because a program doesn't mind dead ends.

puzzles.txt holds Caitlin's three puzzles. read_puzzles is written: it gives back each puzzle as nine rows of nine numbers, with 0 for a blank. In sudoku.py, write:

  1. can_place(grid, row, col, digit): True if digit isn't already in that square's row, its column, or its 3 by 3 box; False if it is.
  2. next_blank(grid): the (row, col) of the first blank square, reading along each row from the top, or None if there are no blanks.
  3. solve(grid): fill in every blank so the puzzle is solved, changing grid itself, and give back True; or, if it can't be solved, give back False with grid exactly as it was. Use backtracking: put the first digit that fits in the next blank and carry on; when a square has no digit that fits, rub out the last digit you wrote and try the next one there.
  4. show(grid): the grid as nine lines of text, . for a blank, a space between squares, | between boxes, and a line of ------+-------+------ between each band of three rows.

The main block solves each puzzle in turn and prints it, or says it can't be done.

What it prints
Puzzle 1
4 5 7 | 2 8 1 | 6 9 3
9 3 6 | 7 5 4 | 2 1 8
1 8 2 | 6 3 9 | 7 4 5
------+-------+------
7 1 5 | 8 9 2 | 3 6 4
2 9 8 | 3 4 6 | 5 7 1
6 4 3 | 5 1 7 | 8 2 9
------+-------+------
3 7 4 | 1 2 5 | 9 8 6
8 6 9 | 4 7 3 | 1 5 2
5 2 1 | 9 6 8 | 4 3 7

Puzzle 2
3 5 8 | 7 2 9 | 1 6 4
9 7 2 | 4 6 1 | 3 8 5
1 4 6 | 5 8 3 | 9 2 7
------+-------+------
4 8 1 | 2 3 5 | 7 9 6
7 6 9 | 8 1 4 | 5 3 2
5 2 3 | 6 9 7 | 4 1 8
------+-------+------
8 3 4 | 9 5 2 | 6 7 1
2 9 5 | 1 7 6 | 8 4 3
6 1 7 | 3 4 8 | 2 5 9

Puzzle 3
No solution. It can't be done.

What you learn

What's in it

  1. Back out of dead ends
  2. No way through
  3. How Paul seats the teams
  4. Fix Yahya's version
  5. Make the sudoku solver
  6. Ship it