📜  数数未按升序排序的列

📅  最后修改于: 2021-04-22 02:42:08             🧑  作者: Mango

给定一个由N个相同长度的小写字母字符串组成的数组A。任务是查找未按升序排序的列数。

例子:

Input: A = ["cba", "dah", "ghi"]
Output: 1
2nd Column ["b", "a", "h"] is not sorted in increasing order.

Input: A = ["zyx", "wvu", "tsr"]
Output: 3
All columns are not sorted in increasing order.

方法:遍历每一列,并检查下一个元素是否大于同一列中的上一个元素。如果不是,则将countOfCol递增1,并继续遍历直到遍历所有列。打印countOfCol的值。

# function to count the unsorted columns
def countUnsorted(A):
  
    countOfCol = 0
  
    for col in zip(*A):
        if any(col[i] > col[i + 1] for i in range(len(col) - 1)):
            countOfCol += 1
  
    return countOfCol
  
# Driver code
A = ["cba", "daf", "ghi"]
print(countUnsorted(A))
输出:
1