Skip to content

Instantly share code, notes, and snippets.

@yyl
Created July 15, 2012 16:41
Show Gist options
  • Save yyl/3117700 to your computer and use it in GitHub Desktop.
Save yyl/3117700 to your computer and use it in GitHub Desktop.
My solution for sudoku checker in online course Software testing
def check_sudoku(grid):
###Your code here.
if isIllFormed(grid):
return None
elif isInvalid(grid):
return False
else:
return True
# return True if the grid is ill_formed
# 1. has a list with !9 size
# 2. has an elment more than 9 or less than 0
# return True if invalid, False otherwise
def isIllFormed(g):
for li in g:
if len(li) != 9:
return True
else:
for i in li:
if i > 9 or i < 0:
return True
else:
return False
# check if the whole grid is invalid
# return True if invalid, False otherwise
def isInvalid(grid):
inval = False
columns = [[] for i in range(len(grid))]
boxes = [[] for i in range(len(grid))]
# check invalid for all rows
# generate lists for columns and boxes
for li in grid:
if inval == False:
inval = checkInvalid(li)
# collect each column of the grid into columns list
map(lambda x, y: y.append(x), li, columns)
# collect each box of the grid into boxes list
row = grid.index(li)
col = 0
for i in li:
boxes[boxNumber(row, col)].append(i)
col += 1
# check invalid for all boxes
for box in boxes:
if inval == False:
inval = checkInvalid(box)
# check invalid for all columns
for li in columns:
if inval == False:
inval = checkInvalid(li)
return inval
def boxNumber(row, col):
return col/3 + (row/3)*3
# check if a single column/row/box is invalid
# return True if invalid, False otherwise
def checkInvalid(li):
count = [0 for i in range(10)]
for i in range(len(li)):
count[li[i]] += 1
if max(count[1:]) > 1:
return True
else:
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment