Pergunta

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!

Foi útil?

Solução

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:]))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top