thorium
thorium

Reputation: 197

check if sorted using recursion in python

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!

Upvotes: 2

Views: 2065

Answers (1)

falsetru
falsetru

Reputation: 369274

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:]))

Upvotes: 6

Related Questions