【问题标题】:Python3 : How to print all diagonals with fixed length in a matrixPython3:如何在矩阵中打印所有固定长度的对角线
【发布时间】:2021-12-27 13:59:42
【问题描述】:

我目前正在从事井字游戏项目。我希望电路板具有自定义尺寸。但我不知道如何检查所有固定长度为 k 的行、列和对角线(k 是可定制的)。这里有一个例子来说明我的意思。

"""
For example if the board is a 4x4 matrix and I want to check the rows, cols, and diagonals of consecutive cells with fixed length of 3
"""
board = [[1, 2, 3, 4]
         [5, 6, 7, 8]
         [9, 10,11,12]
         [13,14,15,16]]
# Print all rows:
# Output: [1,2,3], [2,3,4], [5,6,7], [6,7,8], [9,10,11], [10,11,12], [13,14,15], [14,15,16]

# Print all cols:
# Output: [1,5,9], [5,9,13], [2,6,10], [6,10,14], [3,7,11], [7,11,15], [4,8,12], [8,12,16]

# Print all diagonals (beside 2 main diagonals there're more smaller diagonals):
# Output: [1,6,11], [6,11,16], [4,7,10], [7,10,13], [3,6,9], [2,7,12], [5,10,15], [8,11,14]

【问题讨论】:

    标签: python-3.x matrix tic-tac-toe


    【解决方案1】:

    这是一个带有解释的工作代码。有多种方法可以解决这个问题,您选择的方式将取决于您将如何使用此代码。我选择创建在电路板上迭代的生成器。

    import numpy as np
    board = np.array( [
        [1, 2 ,3 ,4 ],
        [5, 6 ,7 ,8 ],
        [9, 10,11,12],
        [13,14,15,16]
        ])
    

    为了更容易迭代电路板本身,我将其制成了一个numpy 数组,这样对列的迭代就和对行的迭代一样简单,检查尺寸等也是如此。

    您需要的核心代码非常简单:将行、列或对角线传递给此函数和所需的大小,它将产生大小的子列表,直到它不再可以为止。

    
    def get_sublist(line, size):
        i = 0
        length = len(line)
        while i<=length-size:
            yield line[i:i+size]
            i+=1     
    

    然后,您需要做的就是像这样遍历板或转置板:

    #for rows
    for line in board:
        yield from get_sublist(line, size)
    
    #for columns
    for line in board.T
        yield from get_sublist(line, size)
    

    最后,要遍历对角线,您可以使用方便的 numpy.diag 函数并执行完全相同的操作。对于对角线,只需翻转数组:

        #get the diagonals
        for d in range(-size, size+1):
            yield from get_sublist(np.diag(board, d), size)
        
        #get antidiagonals
        board = np.fliplr(board)
        for d in range(-size, size+1):
            yield from get_sublist(np.diag(board, d), size)
    

    总而言之,完整的工作代码如下。我添加了一些检查,以免出现意外错误。我希望你能从中学到一些东西!

    import numpy as np
    board = np.array( [
        [1, 2 ,3 ,4 ],
        [5, 6 ,7 ,8 ],
        [9, 10,11,12],
        [13,14,15,16]
        ])
    
    
    def get_sublist(line, size):
        i = 0
        length = len(line)
        while i<=length-size:
            yield line[i:i+size]
            i+=1            
        
    
    def get_line(board, size, column=True):
        """Get sub-sections of rows or columns of board up to given size. column 
        decides if it iterates over rows or columns"""
        
        if not isinstance(column, bool):
            raise TypeError(f'row should be type bool, not {type(column)}')
        
        if size > board.shape[column]:
            raise ValueError(f'Cant get size {size} rows, board is {board.shape}')
        
        if column: 
            board = board.T
            
        for line in board:
            yield from get_sublist(line, size)
        
            
    def get_diags(board, size):
        """Get sub-sections of the diagonals of the board for the given size"""
         
        if size > board.shape[0]:
            raise ValueError(f'Cant get size {size} rows, board is {board.shape}')
      
        #get the diagonals
        for d in range(-size, size+1):
            yield from get_sublist(np.diag(board, d), size)
        
        #get antidiagonals
        board = np.fliplr(board)
        for d in range(-size, size+1):
            yield from get_sublist(np.diag(board, d), size)
        
    
    print(list(get_line(board, 3, column=True)))
    print(list(get_line(board, 3, column=False)))
    print(lies(get_diags(board, 3)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多