Python 数独验证器 9X9

1 投票
1 回答
3931 浏览
提问于 2025-04-17 22:00
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 个回答

2

首先,几点说明:

绝对不要这样做:

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 循环,或者说用得不对(你真的想在一个异常上无限循环吗?)可以使用命令行参数,这样可以让用户在命令行中选择一个确实存在的文件。

现在我把这些都说清楚了,接下来谈谈你实际的问题:

infile 是一个文件对象(如果我没看错你缩进不对的 Python 代码),所以 infile 中的每一行,称为 row,其实就是一个字符串。

所以如果你有一个空行或者某一行的列数少于 9 列,你可能会遇到 row[i] 超出范围的问题。

下面是对你代码的重构尝试,虽然我留了一些设计上的错误:

    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

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

    def check_grid():
        cols = [[row[i] for row in infile] for i in range(0,9)]
        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")

        inputs()

    def sudoku_checker():
        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
            # Counts the amount of numbers in the sudoku puzzle
            print("The total number in this puzzle is:",len(grid))
            check_grid()
        except FileNotFoundError:
            print ("The inputted file does not exist")

if __name__ == "__main__":
    sudoku_checker()

撰写回答