我有一个矩阵或列表列表:
x = [[1,2,3],
[2,3,1],
[3,1,2]]
我的目标是检查是否
1)矩阵的每一列包含,从1到n的每个整数恰好出现一次。
2) 矩阵的每一行包含从 1 到 n 的每个整数恰好一次。
这是我在解决Udacity的intro to programming类(class)时遇到的问题练习。这是我解决问题的方法。我知道这是漫长而低效的。那么解决这个问题的简短有效方法是什么??
def check(p):
j = 0
for e in p:
i = 1 + j
s = str(p)
if s.find('.')!= -1:
return False
while i < len(p):
if p[i] == e:
return False
if p[i] > len(p) or p[i] < 1:
return False
i += 1
j += 1
return True
def check_sudoku(p):
i = 0
z = []
a = []
x = 0
for e in p:
r = check(e)
if r == False:
return r
#Below here is to transpose the list
while x < len(p):
z.append(1)
x += 1
while i < len(p):
for e in p:
a.append(e.pop())
z[i] = a
i += 1
a = []
#Below here is to check the transpose
for g in z:
r = check(g)
if r == False:
return r
return True
请您参考如下方法:
您可以像这样简化检查程序:
def check_valid(matrix):
n = len(matrix[0])
valid_num = range(1, n+1) # make a list of valid number from 1 to n
# sort rows and column of matrix in ascending order and compare with valid_num
for line in matrix:
if sorted(line) != valid_num:
return False
for column in zip(*matrix):
if sorted(column) != valid_num:
return False
# If all rows and column is valid, then
return True
编辑:遵循@vocalno KISS 规则但速度更快并且适用于数字和字符
def check_valid2(matrix):
n = len(matrix)
for line in matrix+zip(*matrix):
if len(set(line)) != n:
return False
return True
In[9]: %timeit for m in (x, y): check_valid_mine(m)
100000 loops, best of 3: 8.55 µs per loop
In[10]: %timeit for m in [x,y]: check_valid2(m)
100000 loops, best of 3: 5.77 µs per loop
编辑 2:关于速度
def check_valid3(matrix):
n = len(matrix)
for line in matrix+zip(*matrix):
if not len(set(line)) - n:
return False
return True
In[19]: %timeit for m in [x,y]: check_valid3(m)
100000 loops, best of 3: 2.29 µs per loop
