Python 中的数独块检查器

问题描述 投票:0回答:1

这种问题以前曾被问过,但我想出了一个我不经常看到的解决方案。现在,这可以在我的本地主机上运行,但是当我将其输入大学程序时,它会返回我未通过功能检查,但我将其传递到本地主机上。我需要检查带有行和列条目的 3 x 3 块。当我该撒谎的时候我却撒谎了。

    sudoku = [
      [9, 0, 0, 0, 8, 0, 3, 0, 0],
      [2, 0, 0, 2, 5, 0, 7, 0, 0],
      [0, 2, 0, 3, 0, 0, 0, 0, 4],
      [2, 9, 4, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 7, 3, 0, 5, 6, 0],
      [7, 0, 5, 0, 6, 0, 4, 0, 0],
      [0, 0, 7, 8, 0, 3, 9, 0, 0],
      [0, 0, 1, 0, 0, 0, 0, 0, 3],
      [3, 0, 0, 0, 0, 0, 0, 0, 2]
    ]


    def block_correct(sudoku: list, row_no: int, column_no:int):

        correct = [1,2,3,4,5,6,7,8,9]       # this is the list I compare to

        n=0                                 #counter for rows
        b=0                                 #counter for columns
        check_sq= []                        #list i use to compare to correct sudoku list
        col_noin = column_no                #required to remember 3x3 block
        while True:                         #loop for columns
            if b==3:
                break 
    
            while True:                     #loop for rows
                if n==3:
                    break        
                check_sq.append(sudoku[row_no][column_no])     #this adds entries into checking list

                column_no += 1
                n+=1
            b += 1
            row_no += 1
            column_no = col_noin 
            n=0



        if bool(set(correct).difference(check_sq)) == False:    #this determines if loops are the same
            return True
        else:
            return False

    print(block_correct(sudoku,2,2))
python sudoku
1个回答
1
投票

我认为问题是你的

while True
循环与
if b == 3: break
if n == 3: break
没有准确地将遍历限制在有效的 3x3 数独块中。 您的代码可能会超出网格范围,或者不会覆盖整个块,但会覆盖多个有效 3x3 块中不相关的 3x3 块。

尝试添加逻辑以确保

start_row
start_col
有效,如果提供的某些
IndexError
row_no
不完全是左上角的单元格,则当前代码可能会导致
column_no
或不正确的结果有效 3x3 块的:

def block_correct(sudoku: list[list[int]], row_no: int, column_no: int) -> bool:
  correct = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  check_sq = []
  start_row = row_no // 3 * 3 
  start_col = column_no // 3 * 3
  for r in range(start_row, start_row + 3):
    for c in range(start_col, start_col + 3):
      check_sq.append(sudoku[r][c])
  return not set(correct).difference(check_sq)

sudoku = [
  [9, 7, 8, 0, 8, 0, 3, 0, 0],
  [4, 5, 6, 2, 5, 0, 7, 0, 0],
  [1, 2, 3, 3, 0, 0, 0, 0, 4],
  [2, 9, 4, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 7, 3, 0, 5, 6, 0],
  [7, 0, 5, 0, 6, 0, 4, 0, 0],
  [0, 0, 7, 8, 0, 3, 9, 0, 0],
  [0, 0, 1, 0, 0, 0, 0, 0, 3],
  [3, 0, 0, 0, 0, 0, 0, 0, 2],
]
print(block_correct(sudoku, 0, 0))  # True
print(block_correct(sudoku, 8, 8))  # False but would throw an IndexError with your current code
© www.soinside.com 2019 - 2024. All rights reserved.