Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a built-in function in Python that allows you to check the number of items that are already sorted in an array?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading