给定矩阵mat [] [] ,任务是计算按降序排序的列数。
例子:
Input: mat[][] = {{1, 3}, {0, 2}}
Output: 2
First column: 1 > 0
Second column: 3 > 2
Hence, the count is 2
Input: mat[][] = {{2, 2}, {1, 3}}
Output: 1
方法:逐行遍历每一列,并检查同一列中的下一个元素是否≥前一个元素。如果条件对于所有可能的元素均有效,则将计数增加1 。遍历所有列后,打印count 。
下面是上述方法的实现:
Python3
# Python3 program to count the number of columns
# in a matrix that are sorted in descending
# Function to count the number of columns
# in a matrix that are sorted in descending
def countDescCol(A):
countOfCol = 0
for col in zip(*A):
if all(col[i] >= col[i + 1] for i in range(len(col) - 1)):
countOfCol += 1
return countOfCol
# Driver code
A = [[1, 3], [0, 2]]
print(countDescCol(A))
输出:
2