如何检查列和子网格(Python中的Sudoku Checker)?

时间:2017-10-30 03:03:04

标签: python python-3.x function file sudoku

我正在做传统的" Sudoku Puzzle Checker"活动,我到目前为止只能弄清楚如何检查行。根据指令,我想检查(在3个单独的函数中)解决的数独谜题的行,列和子网格(3x3方格)(在.csv文件中给出)。我理解如何来做列(每次添加9次,9次起始数字从0到8)和子网格(3个数字的范围,添加6以获得下一个3个数字范围)等)但我很困惑如何将这些概念实现到我的代码中。这就是我现在所拥有的:

def load_puzzle(filename):

    file = open(filename, 'r')

    puzzle = list(file)

    #the puzzle currently looks like this:
    ['5,3,4,6,7,8,9,1,2\n', '6,7,2,1,9,5,3,4,8\n', '1,9,8,3,4,2,5,6,7\n', '8,5,9,7,6,1,4,2,3\n', '4,2,6,8,5,3,7,9,1\n', '7,1,3,9,2,4,8,5,6\n', '9,6,1,5,3,7,2,8,4\n', '2,8,7,4,1,9,6,3,5\n', '3,4,5,2,8,6,1,7,9\n']

    print_puzzle(puzzle)



def print_puzzle(puzzle):

    print(" ")

    count = 0

    while count <= 8:
        line = list(puzzle[count])
        line = [x for x in line if x != ',']
        line.remove('\n')
        line.insert(3, '|')
        line.insert(7, '|')
        if count == 3 or count == 6:
            print("---------------------")
        fresh = ' '.join(line)
        count += 1

    print('''
Checking puzzle...
    ''')

    delimiter = ','
    together = delimiter.join(puzzle)
    new = list(together)
    new[:] = [x for x in new if x != ',']
    new[:] = [x for x in new if x != '\n']

    check_rows(new)

    #the puzzle now looks like this:
    ['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']

def check_numbers(numbers):

    my_list = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

    numbers.sort()

    if numbers == my_list:
        return True
    else:
        return False



def check_rows(n):

    count = 0
    start = 0

    while count <= 8:
        row = n[start:(start + 9)]

        if check_numbers(row) is True:
            count += 1
            start += 9
        elif check_numbers(row) is False:
            break

    if count == 9:
        print("Rows okay...")
    else:
        print("Error in row", count)


    check_columns(n)


def check_columns(n):

    count = 0
    start = 0

    while count <= 8:
        col = n[start::9]

        if check_numbers(col) is True:
            count += 1
            start += 1
        elif check_numbers(col) is False:
            break

    if count == 9:
        print("Columns okay...")
    else:
        print("Error in row", count)  

def check_subgrids(n):


filename = input("Enter file name of solved sudoku puzzle: ")

load_puzzle(filename)

我正在寻找一种方法来查找列和子网格,类似于我找到行的方式(即row = n[start:(start + 9)]),如果可能的话。我是初学者,所以我也很高兴能够了解我可以改进代码的不同工具/方法!

编辑:我已经用check_columns函数解决了我的问题(代码已更新),但仍然会对check_subgrid函数提供一些指导!

0 个答案:

没有答案