Problem description
I am attempting to define a function that counts the maximum number of items in an array that are already sorted based on any given array. For example,
[1, 2, 3] should return 3 as it is fully sorted, [3, 2, 1] should return 0, and 0, 2, 1 should return 2. Can anyone help me? Thanks!
>Solution :
We can create a one-liner function (no builtin exists)
Code
def count_ordered(lst):
return sum(x==y for x, y in zip(lst, sorted(lst)))
Tests
count_ordered([0, 1, 2]) # returns 3
count_ordered([0, 2, 1]) # returns 1
count_ordered([3, 2, 1]) # returns 1
Explanation
The function counts the number of elements that match before and after sorting.