📜  矩阵中包含重复值的行数和列数

📅  最后修改于: 2021-09-04 07:49:58             🧑  作者: Mango

给定一个N x N方阵arr[][] ,它只包含 1 到 N 之间的整数,任务是计算矩阵中包含重复值的行数和列数。

例子:

方法:想法是使用 NumPy 库。

  • 为方阵中的每一行和每一列创建一个 NumPy 数组。
  • 求唯一元素的长度。
  • 如果长度等于N ,则该特定行或列中不存在重复值。

下面是上述方法的实现:

# Python program to count the number of 
# rows and columns in a square matrix 
# that contain repeated values
  
import numpy as np
  
# Function to count the number of rows
# and number of columns that contain 
# repeated values in a square matrix.
def repeated_val(N, matrix):
    column = 0
    row = 0
    for i in range (N):
  
    # For every row, an array is formed. 
    # The length of the unique elements 
    # is calculated, which if not equal 
    # to 'N' then the row has repeated values.
        if (len(np.unique(np.array(matrix[i])))!= N):
            row += 1 
  
    # For every column, an array is formed.
    # The length of the unique elements 
    # is calculated, which if not equal 
    # to N then the column has repeated values.
    for j in range (N):
        if (len(np.unique(np.array([m[j] for m in matrix])))!= N):
            column += 1
              
    # Returning the count of 
    # rows and columns
    return row, column
  
  
# Driver code
if __name__ == '__main__': 
  
     
    N = 3
    matrix = [ [ 2, 1, 3 ], [ 1, 3, 2 ], [ 1, 2, 3 ] ]
  
    print(repeated_val(N, matrix))  
输出:
(0, 2)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live