Python Sudoku Checker 9X9

时间:2014-03-12 18:17:39

标签: python

while True:
    try:
        file = input("Enter a filename: ") 
        fi = open(file, "r")
        infile = fi.read()
        grid = [list (i) for i in infile.split()] #Puts the sudoku puzzle into a list in     order to check that the total number is valid
        check = len(grid)
        print("The total number in this puzzle is:",check) #Counts the amount of numbers in the sudoku puzzle
        break
    except FileNotFoundError:
        print ("The inputted file does not exist")

def check(infile):
    count = 0
    for j in range (0,9):
        for n in range(0,9):
            if infile[j].count(infile[j][n]) <= 1:
                count = count + 0
            else:
                count = count + 1

cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
leg = 0
for i in range(0,9):
    for j in range(0,9):
        if cols[i].count(cols[i][j]) <= 1:
            leg = leg + 0
        else:
                leg = leg + 1

angel = []
for t in range(3):
    ang = infile[t]
    for u in range(3):
        angel.append(ang[u])

        foot = 0
        for be in range(9):
            if angel.count(angel[be]) <= 1:
                foot = foot + 0
            else:
                    foot = foot + 1


if count + leg + foot == 0:
    print("Valid")
else:
    print ("Invalid")


def inputs():
    x = raw_input()
    ls = []
    while x != '':
        x1 =x.split(' ')
        ls.append(x1)
        if len(infile) >=9:
            print (check(infile))
            infile = []
            x = raw_input()
inputs() 

实际错误:

Traceback (most recent call last):
  File "E:/Computer Programming/Assignment/check 2.py", line 22, in <module>
    cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
  File "E:/Computer Programming/Assignment/check 2.py", line 22, in <listcomp>
    cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
  File "E:/Computer Programming/Assignment/check 2.py", line 22, in <listcomp>
    cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
IndexError: string index out of range

为什么它给出一个输出来说我的字符串索引超出范围,是否有另一种方法来创建一个数独的9x9检查器来检查是否有任何重复出现的数字。我需要确保每列中有9个数字,并且它们位于数字1和9之间

1 个答案:

答案 0 :(得分:0)

首先,一些评论:

从不执行:

cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]

但是:

 cols = [[row[i] for row in infile] for i in range(0,9)]
  • 永远不要将变量与您在代码checkcheck()
  • 中定义的函数调用相同的名称
  • 不要在模块级别编写代码,而是将所有内容嵌入到函数中,并在if __name__ == "__main__"条件之后调用文件末尾的入口点函数(以防您想要导入另一个模块中的模块,你不执行模块级代码)。
  • 不打开文件而不关闭它们,而是使用上下文管理器:with open('myfile', 'r') as f: ...
  • 你的代码使用了while ......或者至少是错误的使用(你真的是要永远循环一个异常吗?)而是使用命令行参数,这将使shell帮助你用户选择实际存在的文件。

现在我已经清楚地说明了这一点,关于你的实际问题:

infile是一个文件对象(如果我能正确读出你的错误缩进的python代码),那么row中每一行infile只是一个字符串。< / p>

因此,如果您有一个空行或少于9列的行,您可能会超出边界{/ 1}。

这是重构代码的一种尝试,尽管我已经留下了一些错误的设计:

row[i]