Question

I am trying to check if a list is sorted using recursion in python. Returns true if sorted, False if not sorted.

def isSorted(L):
    if len(L) < 2:
       return True

Now, I am not sure what I should be doing next.Please help!

Was it helpful?

Solution

Check first two items.

If they are ordered, check next items using recursion:

def isSorted(L):
    if len(L) < 2:
        return True
    return L[0] <= L[1] and isSorted(L[1:])

Side note The function can be expression as a single expression as thefourtheye commented:

return len(L) < 2 or (L[0] <= L[1] and isSorted(L[1:]))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top