数独验证器列和单元格

时间:2015-03-12 00:14:01

标签: python python-3.x

我正在编写一个程序,它将获取用户.txt文件并验证数独。这是一个文件的例子

5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9

到目前为止,在我的代码中,我试图让它检查行,但它没有检查每一行。相反,它将此作为输出。

{' ', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
true
{' ', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
true
{' ', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
true
{' ', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
true
{' ', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
true
{' ', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
true
{' ', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
true
{' ', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
true
{' ', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
true

这是我的代码。另外我想知道如何检查列和单元格

file=input("Enter a filename: ")
fi=open(file,"r")
f=fi.read()
row=f.split("\n")
check=set(row)
print(check)
for n in check:
    seen=set(n)
    print (seen)
    if len(seen)<9:
        print ("false")
    else:
        print ("true")

1 个答案:

答案 0 :(得分:0)

尝试这种枚举技术,我检查行和列的子总数为45:

with open('data.txt') as data:

    row_total = [0 for i in range(9)]
    col_total = [0 for i in range(9)]

    for a, b in enumerate(data):

        sb_row_total = 0

        for c, d in enumerate(b.split()):

            sb_row_total += int(d)
            col_total[c] += int(d)

        row_total[a] = sb_row_total

    rows = all(i == 45 for i in row_total)
    cols = all(i == 45 for i in col_total)

    print(rows and cols)