数独 - 检查行列中是否有重复项
Sudoku - checking if there are duplicates in rows&columns
所以我的目标是编写一个程序,从每一行和每一列中提取非零整数,并检查是否有任何重复值,如果存在重复则return False,否则return真的。
它适用于行,但我正在努力获取每列中的非零条目。我只能从一个特定的列中获取非零条目,但我不知道如何遍历所有列并检查重复项。
我试过使用嵌套的 for 循环,但它似乎不起作用,因为它只是 return L.
中每个列表中的所有非零整数的列表
def sudoku(L):
#checks the rows
for i in L:
row=[x for x in i if x != 0]
for j in row:
if row.count(j)!=1:
return False
#checks the columns
col=list()
for x in range(9):
if L[x][0]!=0:
col.append(L[x][0])
print(col)
L = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]
print(sudoku(L))
我的方法是将每一列的相同索引转换为一行,并为行重复使用代码
L = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]
columns = []
for i in range(len(L)):
columns.append([])
for row in L:
if row[i] != 0:
columns[i].append(row[i])
print(columns) #List of columns with no 0’s
column = [[x[count] for x in L if x[count] != 0] for count in range(9) ]
for c in column:
if len(set(c)) != len(c):
return False
else:
return True
set()
删除所有重复项
代码可以缩短为
column = [[x[count] for x in L if x[count] != 0] for count in range(9) ]
return False not in [True if len(set(c)) == len(c) else False for c in column]
所以我的目标是编写一个程序,从每一行和每一列中提取非零整数,并检查是否有任何重复值,如果存在重复则return False,否则return真的。 它适用于行,但我正在努力获取每列中的非零条目。我只能从一个特定的列中获取非零条目,但我不知道如何遍历所有列并检查重复项。 我试过使用嵌套的 for 循环,但它似乎不起作用,因为它只是 return L.
中每个列表中的所有非零整数的列表 def sudoku(L):
#checks the rows
for i in L:
row=[x for x in i if x != 0]
for j in row:
if row.count(j)!=1:
return False
#checks the columns
col=list()
for x in range(9):
if L[x][0]!=0:
col.append(L[x][0])
print(col)
L = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]
print(sudoku(L))
我的方法是将每一列的相同索引转换为一行,并为行重复使用代码
L = [[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]
columns = []
for i in range(len(L)):
columns.append([])
for row in L:
if row[i] != 0:
columns[i].append(row[i])
print(columns) #List of columns with no 0’s
column = [[x[count] for x in L if x[count] != 0] for count in range(9) ]
for c in column:
if len(set(c)) != len(c):
return False
else:
return True
set()
删除所有重复项
代码可以缩短为
column = [[x[count] for x in L if x[count] != 0] for count in range(9) ]
return False not in [True if len(set(c)) == len(c) else False for c in column]