Python列重复检查器
有人能告诉我如何检查数字列中的重复项吗?我已经知道了如何查找行中的重复项。这是一个数独网格9x9。干杯您应该为每一行和每一列设置一个Python列重复检查器,python,Python,有人能告诉我如何检查数字列中的重复项吗?我已经知道了如何查找行中的重复项。这是一个数独网格9x9。干杯您应该为每一行和每一列设置一个seed,总共18个。然后,每读一个数字,检查行的seen和列的seen中的成员身份。这不是效率方面的最佳方法,但理解起来很简单。我认为对于9x9网格,可理解性比速度更重要 有一个矩阵,行操作很容易,所以让我们转置它。当我们的行变成列时,我们可以再次使用anydup_row函数 我将假设所有行都是完整的,并且文件中的数据由空格分隔 file = input("Ent
seed
,总共18个。然后,每读一个数字,检查行的seen
和列的seen
中的成员身份。这不是效率方面的最佳方法,但理解起来很简单。我认为对于9x9网格,可理解性比速度更重要
有一个矩阵,行操作很容易,所以让我们转置它。当我们的行变成列时,我们可以再次使用anydup_row函数
我将假设所有行都是完整的,并且文件中的数据由空格分隔
file = input("Enter a filename: ")
fi = open(file, "r")
for line in fi:
line = line.split()
c = len(line)
print(line)
print (c)
def anydup(line): # Checks for duplicates in the rows
seen = set()
for x in line:
if x in seen:print("There are some duplicate numbers in the rows")
seen.add(x)
print("There are no duplicates in the rows")
infle=input(“输入文件名:”)#不要使用python内置名称!
fi=开放式(填充“r”)
矩阵=映射(lambda x:x.split(),fi.readlines())
def anydup_行(矩阵):#检查行中是否存在重复项
重复=[False]*9
对于i,枚举(矩阵)中的行:
如果len(设置(行))<9:
重复[i]=True
回击
def anydup_列(矩阵):
矩阵\u T=zip(*矩阵)
返回任意DUP行(矩阵)
这就是检查重复项所需的全部内容。显然,它也不能确保条目是1-9,但这似乎是理所当然的
infile = input("Enter a filename: ") #Don't use python builtins for names!
fi = open(infile, "r")
matrix = map(lambda x: x.split(), fi.readlines())
def anydup_row(matrix): # Checks for duplicates in the rows
dupes = [False] * 9
for i, row in enumerate(matrix):
if len(set(row)) < 9:
dupes[i] = True
return dupes
def anydup_columns(matrix):
matrix_T = zip(*matrix)
return anydup_row(matrix_T)
您能给我一个例子吗?对于较旧版本的python,可能必须使用原始输入,或者依赖用户在输入文件名周围加引号。
fi = input("Enter a filename: ")
grid = [line.split() for line in open(fi)]
for row in grid:
assert len(set(row)) == 9
for col in range(9):
assert len(set(row[col] for row in grid)) == 9