如何检查数字是否在 3x3 网格中重复?

how do I check if numbers repeat in a 3x3 grid?

def isSudokuBox(B):
    for i in range(0, 3):
        for z in range(0, 3):
            if int(B[i][z]) <= 0:

                return False
                continue
            elif int(B[i][z]) > 9:

                return False
                continue

所以我制作了检查数字是否从 1 到 9 的部分并且它有效,但我不知道如何让它检查存在不止一次的元素。我能做什么?一种方法是只为每种可能的情况制作条件,但这非常乏味而且不是很漂亮。肯定还有别的办法。

所述数组的示例如下所示:

A3 = [[9,8,2],
[1,3,5],
[6,2,1]]

当我将 A3 作为参数传入时,如何创建一个算法 returns 上述函数为假?

你可以做的是拥有一个包含 9 个 0 的数组:

numCounts = [0,0,0, 0,0,0, 0,0,0]

每次当你看到一个数字递增时,它就是索引。如果索引变得大于 1,那么你有一个重复的数字:

numCounts[number]+=1
if(numCounts[number] > 1):
    print("duplicate " + str(number))


def isSudokuBox(B):
    numCounts = [0,0,0, 0,0,0, 0,0,0]
    for i in range(0, 3):
        for z in range(0, 3):
            if int(B[i][z]) <= 0:
                return False
            elif int(B[i][z]) > 9:
                return False
            # here we use the number as the index
            # -1 in order to get values from 0 to 8 which will correspond to the locations of those numbers in the array.
            numCounts[B[i][x]-1]+=1
            if(numCounts[B[i][x]-1] > 1):
                return False
   return True # if we get till the end we know that it is a Sudoku box

假设你有一个 3x3 numpy 数组

import numpy as np
(np.sort(arr.reshape(-1)) == np.arange(1, 10)).all()

示例:

x_complete = np.array([[3, 5, 1],
                      [2, 4, 7],
                      [6, 8, 9]])
(np.sort(x_comp.reshape(-1)) == np.arange(1, 10)).all()

结果

True

同时

x_incomplete = np.array([[3, 3, 1],
                          [2, 4, 7],
                          [6, 8, 9]])
(np.sort(x_incomplete.reshape(-1)) == np.arange(1, 10)).all()

False

首先,我们将 3x3 数组重塑为一维数组。现在我们可以对数组进行排序,并且可以将这个数组与预期的数组 np.array([1,2,3,4,5,6,7,8,9]) 进行比较(我只是使用 shorthand 表示法)。由于我们逐个比较元素以便返回布尔数组,因此我们检查所有元素是否相同。

numpy解决方案

为了将它与您的其余代码一起使用,您可以:

import numpy as np
def isSudokuBox(B):
    arr = np.array(B)
    return (np.sort(arr.reshape(-1)) == np.arange(1, 10)).all()

使用 reduce 和内置的解决方案

如果您不想使用 numpy,可以使用

from functools import reduce
def isSudokuBox(B):
    return sorted(reduce(lambda x,y: x+y, B)) == list(range(1,10))
x = [[1,1,1], [4,4,4],[7,7,7]]
y = [[1,2,3], [4,5,6],[7,8,9]]

def has_dups(ob):
    flat = [x2 for x1 in ob for x2 in x1]
    return len(flat) != len(set(flat))

print(has_dups(x))
print(has_dups(y))