如果[Python]

时间:2018-01-12 02:33:39

标签: python python-3.x

我是个新手,因为这个问题一直在撞墙。我确信它非常简单,我无法弄明白。我遇到的麻烦是验证序列中的所有数字是否缺少。例如,假设我要验证数独的方形行和列是否有效。每行和每列必须以1到n的数字以任何顺序排列一次。如果数独方块的长度为3,则数字1,2和3应按行和列中的任何顺序出现。我的代码检查了这一点,但是我无法检查是否有像这样的行或列:

[4,4,1,2]

缺少3.这是我用这段代码得到的:

for ith, col in enumerate(matrix):
       for num in col:
          for i in range(1, seq + 1)

以下是问题的所有要求:

# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.

# Define a procedure, check_sudoku,
# that takes as input a square list
# of lists representing an n x n
# sudoku puzzle solution and returns the boolean
# True if the input is a valid
# sudoku square and returns the boolean False
# otherwise.

# A valid sudoku square satisfies these
# two properties:

#   1. Each column of the square contains
#       each of the whole numbers from 1 to n exactly once.

#   2. Each row of the square contains each
#       of the whole numbers from 1 to n exactly once.

# You may assume the the input is square and contains at
# least one row and column. 

correct = [[1, 2, 3],
           [2, 3, 1],
           [3, 1, 2]]

incorrect = [[1, 2, 3, 4],
             [2, 3, 1, 3],
             [3, 1, 2, 3],
             [4, 4, 4, 4]]

incorrect2 = [[1, 2, 3, 4],
              [2, 3, 1, 4],
              [4, 1, 2, 3],
              [3, 4, 1, 2]]

incorrect3 = [[1, 2, 3, 4, 5],
              [2, 3, 1, 5, 6],
              [4, 5, 2, 1, 3],
              [3, 4, 5, 2, 1],
              [5, 6, 4, 3, 2]]

incorrect4 = [['a', 'b', 'c'],
              ['b', 'c', 'a'],
              ['c', 'a', 'b']]

incorrect5 = [[1, 1.5],
              [1.5, 1]]

correct2 = [[1, 2, 3, 4],
            [2, 4, 1, 3],
            [3, 1, 4, 2],
            [4, 3, 2, 1]] 

这是我到目前为止编写的代码:

def checkSquare(square): # Checks to see if it's a perfect square matrix(3X3, 4X4, etc)

    colLen = len(square[0]) # Counts the number of columns in matrix
    rowLen = len(square) # Counts the number of rows in the matrix

    #print("Check the length of the columns:", colLen)
    #print("Check the length of the rows:", rowLen)
    if colLen == rowLen:
        #print("True")
        return True
    else:
        #print("False")
        return False

def checkSequenceRow(square):
    seq = len(square) # seq is the 'n' in 1 to n
    for row in range(len(square)):
        for num in range(1, seq+1): # for loop that will go from 1 to seq or 'n'
            if num not in square[row]: # if num not in the row
                print("False")
                return False
        row = row + 1
    print("True")
    return True

''''''
def checkSequenceCol(square):
    seq = len(square)
    columns = zip(*square)
    for icol, column in enumerate(columns):
        for col in column:
            if col not in range(1, seq + 1):
                print("False")
                return False
    print("True")
    return True

def check_sudoku(square):
    if checkSquare(square) & checkSequenceRow(square) & checkSequenceCol(square) == True:
        print("True")
        return True
    else:
        print("False")
        return False

checkSequenceCol(incorrect)

任何帮助都会很棒。

4 个答案:

答案 0 :(得分:1)

您可以为此目的使用python的Set。

假设您有一个长度为<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>的数组a,并且您想知道它是否从1到n,您可以这样检查:

n

左侧从set(a) == set(range(1, len(a) + 1))创建一个集合,而右侧生成集合a。如果它们相同,您应该能够声明{1, 2, ..., n}包含从1到a的所有元素。

在上面的示例中,n会产生一组set([4, 4, 1, 2]),因此它不等于理想的集合{1, 2, 4}

答案 1 :(得分:0)

我会使用set进行比较: set创建一组唯一项,如果所有元素在两个集合中共享,则两个集之间的比较仅为True。您可以获取一组行或列,然后将其与从行或列的len创建的集合(从1开始的范围)进行比较。为了访问列,我将列表列表转换为numpy数组。

def check_row(square):
    for row in square:
        if set(row) != set(range(1, len(row) + 1)):
            print(False)
            return False
    print(True)

def check_col(square):
    # Numpy array 
    square = np.array(square)
    for i in range(square.shape[1]):
        # Select the column
        col = square[i, :]
        if set(col) != set(range(1, len(col) + 1)):
            print(False)
            return False
    print(True)

这会传递您提供的所有测试用例。

答案 2 :(得分:0)

我会尝试一下。我会给你checkSequenceRow,希望你能适应其他功能。根据您的描述,您缺少的是您已经看过的数字记录,因此[4,4,1,2]。这段代码接近你所做的,所以它应该很容易理解,但Python的集合是一种更好,更pythonic的方式。我鼓励你去调查一下。

def checkSequenceRow(square):
    for row in range(len(square)):  # go row by row
        seen = []
        n = len(row)
        for number in range(len(row)): # validate the row
            if number in seen: # found a duplicate
                return False
            elif number < 1 or number > n: # found an invalid value
                return False
            else:
                seen.append(number) # keep track of this valid value
    return True

答案 3 :(得分:0)

只需添加到 Maokai 答案中即可使其更简单:

a = [4,4,1,2]
b = set(range(1, len(a) + 1)).difference(set(a))
print(sorted(list(b)))

上面的代码将从提供的数组中打印缺失的数字作为列表