2014-03-12 30 views
1
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") 

有人可以告訴我如何檢查數字列中的重複項,我已經發現如何在行中找到重複項。這是一個數獨網格9x9。歡呼聲Python Column Duplicate Checker

回答

0

您應該爲每行和每列設置一個seen,共計18個。然後讀取每個數字,檢查行seen和列seen的成員資格。

+0

請你給我一個例子 – user3396351

0

這不是效率方面的最佳方法,但它理解起來非常簡單。我認爲在9x9網格中,可理解性比速度更重要。

你有一個矩陣,行操作很容易,所以讓我們轉置它。當我們的行成爲我們的列時,我們可以再次使用anydup_row函數。

我打算假定這些行都已完成,並且文件中的數據由空格分隔。

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) 
0

這是所有你需要檢查重複。顯然它不能確保條目是1-9,但這似乎被認爲是理所當然的。

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 
+0

可能要使用的的raw_input舊版本的Python,還是要靠用戶將圍繞輸入文件名引號。 – mehtunguh