306. Python Program to Check a Sudoku Grid
HardPhase 3 · Challenge
This one takes a few steps, but you know every tool it uses: strings, slices, lists and for loops with break. Sketch a 9 by 9 grid on paper first and mark where box 5 is.
Overview
Sudoku is a number puzzle played all over the world. Checking a finished grid is good practice with rows, columns and blocks, the same skills you need for any table of data.
Problem Statement
Dmitri solved a Sudoku on the bus and wants to know if the answer is right. Read a filled 9 by 9 grid of digits. The grid is valid when each digit from 1 to 9 appears exactly once:
- in every row,
- in every column,
- in every 3 by 3 box.
The 9 boxes are numbered like this, left to right and top to bottom:
1 2 3
4 5 6
7 8 9
Check the groups in this order, and stop at the first one that breaks the rule:
- rows 1 to 9, from top to bottom,
- then columns 1 to 9, from left to right,
- then boxes 1 to 9.
If every group is right, print Valid. If not, print Not valid: and the name of the first wrong group, in small letters: for example Not valid: row 5, Not valid: column 1 or Not valid: box 4.
Examples
Example 1. Input:
534678912
672195348
198342567
859761423
426853791
713924856
961537284
287419635
345286179
gives:
Valid
Why: every row, every column and every box holds the digits 1 to 9 once each.
Example 2. Input:
354678912
672195348
198342567
859761423
426853791
713924856
961537284
287419635
345286179
gives:
Not valid: column 1
Why: this is the grid of Example 1 with the first two digits swapped. Row 1 still has every digit, so all rows pass. But column 1 now has 3 twice and no 5, and columns come before boxes.
Input
Nine lines, one for each row from top to bottom. Each line has exactly 9 digits from 1 to 9, with no spaces. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: Valid, or Not valid: and the first wrong group. The tests try 8 different inputs.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.