# THREE GOLD STARS
# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.
# Define a procedure, check_sudoku,
# that takes as input a square list
# of lists representing an n x n
# sudoku puzzle solution and returns the boolean
# True if the input is a valid
# sudoku square and returns the boolean False
# otherwise.
# A valid sudoku square satisfies these
# two properties:
# 1. Each column of the square contains
# each of the whole numbers from 1 to n exactly once.
# 2. Each row of the square contains each
# of the whole numbers from 1 to n exactly once.
# You may assume the the input is square and contains at
# least one row and column.
def test_case(l) : test = [] for i in range(1, l + 1) : test.append(i) return test
def check_sudoku(input):
# test each row
for e in input :
test = test_case(len(input))
for m in e :
if m in test:
test.remove(m)
else :
return False
# test each column
for i in range(0, len(input)) :
test = test_case(len(input))
for j in range(0, len(input)) :
if input[j][i] in test :
test.remove(input[j][i])
else :
return False
return True`
巧妙的地方在于为了避免输入数组的每一行和每一列的数据无重复,生成一个list后,数组中每出现一个元素则将其在test列表中删除,保证了对重复元素的检验。
网友评论