首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python Sudoku Checker 9X9

Python Sudoku Checker 9X9
EN

Stack Overflow用户
提问于 2014-03-12 18:17:38
回答 1查看 3.9K关注 0票数 1
代码语言:javascript
运行
复制
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() 

实际错误:

代码语言:javascript
运行
复制
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

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

EN

回答 1

Stack Overflow用户

发布于 2014-03-12 18:31:44

首先,有几点评论:

从不做:

代码语言:javascript
运行
复制
cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]

但要做到:

代码语言:javascript
运行
复制
 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代码),因此infile的每一行(这里称为row )都只是一个字符串。

因此,如果您有一个空行或小于9列的行,则很可能会使row[i]脱离边界。

这里是重构您的代码的一个步骤,尽管我已经留下了一些错误的设计:

代码语言:javascript
运行
复制
    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()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22360418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档