Created
August 16, 2012 15:02
-
-
Save kleino/3370847 to your computer and use it in GitHub Desktop.
Problem Set 3 Sudoku checker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ill_formed = [[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], # <--- | |
[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]] | |
# check_sudoku should return True | |
valid = [[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]] | |
# check_sudoku should return False | |
invalid = [[5,3,4,6,7,8,9,1,2], | |
[6,7,2,1,9,5,3,4,8], | |
[1,9,8,3,8,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]] | |
# check_sudoku should return True | |
easy = [[2,9,0,0,0,0,0,7,0], | |
[3,0,6,0,0,8,4,0,0], | |
[8,0,0,0,4,0,0,0,2], | |
[0,2,0,0,3,1,0,0,7], | |
[0,0,0,0,8,0,0,0,0], | |
[1,0,0,9,5,0,0,6,0], | |
[7,0,0,0,9,0,0,0,1], | |
[0,0,1,2,0,0,3,0,6], | |
[0,3,0,0,0,0,0,5,9]] | |
# check_sudoku should return True | |
hard = [[1,0,0,0,0,7,0,9,0], | |
[0,3,0,0,2,0,0,0,8], | |
[0,0,9,6,0,0,5,0,0], | |
[0,0,5,3,0,0,9,0,0], | |
[0,1,0,0,8,0,0,0,2], | |
[6,0,0,0,0,4,0,0,0], | |
[3,0,0,0,0,0,0,1,0], | |
[0,4,0,0,0,0,0,0,7], | |
[0,0,7,0,0,0,3,0,0]] | |
import numpy | |
def check_ill_formed(grid): | |
assert len(grid) == 9 | |
s = set() | |
for l in grid: | |
if len(l) != 9: | |
return False | |
s|=set(l) | |
res = s - set([0,1,2,3,4,5,6,7,8,9]) | |
if len(res) != 0: | |
return False | |
return True | |
def check_line(li): | |
li = [i for i in li if i!=0] | |
if not len(li) == len(set(li)): | |
return False | |
else: | |
return True | |
def check_sudoku(grid): | |
if not check_ill_formed(grid): | |
return None | |
#check lines | |
for c in numpy.array_split(grid,9,0): | |
if not check_line(list(c.flatten())): | |
return False | |
#check columns | |
for c in numpy.array_split(grid,9,1): | |
if not check_line(list(c.flatten())): | |
return False | |
#check subgrids | |
for c in numpy.array_split(grid,3,1): | |
for r in numpy.array_split(c,3,0): | |
if not check_line(list(r.flatten())): | |
return False | |
return True | |
assert check_sudoku(ill_formed) == None | |
assert check_sudoku(valid) == True | |
assert check_sudoku(invalid) == False | |
assert check_sudoku(easy) == True | |
assert check_sudoku(hard) == True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment