# Sudoku Checker

#!/usr/bin/env python # # Sudoku checker # Take 9 lists of 9 numbers and check whether or not it is a valid sudoku def get_sudoku(): sudoku = [] print 'Input the sudoku' for i in range(9): sudoku.append(raw_input().split(' ')) if len(sudoku[i]) != 9: print 'Really? Since when was a sudoku row not 9 numbers?' return False for n in sudoku[i]: if (len(n) !=1) or (not n.isdigit()) or n=='0': # negative entries & entries greater than 9(2 or more digits), not digits or less than 1 are weeded out print 'Enter a valid sudoku!' return False return sudoku def check_sudoku(sudoku): if not sudoku: return False row=[] column=[] box=[] for i in range(9): row.append([]) column.append([]) box.append([]) for r in sudoku: i= sudoku.index(r) for c in r: j= r.index(c) if c in row[i] or c in column[j] or c in box[(i/3)*3+j/3]: return False else: row[i].append(c) column[j].append(c) box[(i/3)*3+j/3].append(c) return True s = get_sudoku() print check_sudoku(s)
My solution has two functions, get_sudoku(), which takes a sudoku as input from the user, and check_sudoku(list), which checks the sudoku for correctness, well checks for a few things, a lot of the checking work is shared by the get_sudoku function.

### 5 Responses

hi, could you show me what exactly do we need to enter in python in order to get the function to work because when i start the function and it asks for a sudoku I give the following answer:
[5,3,4,6,7,8,9,1,2],
[6,7,2,1,9,5,3,4,8],
[1,9,8,3,4,2,5,6,7],
[8,5,9,7,6,1,4,2,3],
[4,2,6,8,5,3,7,9,1],
[7,1,3,9,2,4,8,5,6],
[9,6,1,5,3,7,2,8,4],
[2,8,7,4,1,9,6,3,5],
[3,4,5,2,8,6,1,7,9]

and the program gives an error.
@Daniel Tinchev Daniel, the script expects 9 lints of space separated numbers. If you are running the script, then enter this as the input

5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9

The input to `check_sudoku` needs to be an array of arrays. So if you are calling `check_sudoku` directly, then try using this

[[5,3,4,6,7,8,9,1,2],
[6,7,2,1,9,5,3,4,8],
[1,9,8,3,4,2,5,6,7],
[8,5,9,7,6,1,4,2,3],
[4,2,6,8,5,3,7,9,1],
[7,1,3,9,2,4,8,5,6],
[9,6,1,5,3,7,2,8,4],
[2,8,7,4,1,9,6,3,5],
[3,4,5,2,8,6,1,7,9]]
I tried what you said, but it is still not working. When I tried with the first option you gave it says the following:
Traceback (most recent call last):