Sebastian S
Sebastian S

Reputation: 337

How to stop recursive function before index out of range?

def isIncreasing(ls):
if not ls:
    print "List empty or to short"
    return
return (False if ls[0] > ls[1] else isIncreasing(ls[1:]))

I have made this to check if list is sorted. How can I make the function stop when there is no more to check?

Im getting the error

"List index out of range".

Upvotes: 1

Views: 588

Answers (1)

ThePavolC
ThePavolC

Reputation: 1738

Just add:

  • checking if only two elements in list
  • checking if just one element or no element in list

Code:

def isIncreasing(ls):
    if len(ls) < 2:
        print "List empty or to short"
        return
    if len(ls) == 2:
        return ls[0] < ls[1]
    return (False if ls[0] > ls[1] else isIncreasing(ls[1:]))

print "{}", isIncreasing({})
print "[]", isIncreasing([])
print [1,2,3], isIncreasing([1,2,3])
print [4,6,8], isIncreasing([4,6,8])
print [2,1,2,3], isIncreasing([2,1,2,3])
print [1,2,3,2], isIncreasing([1,2,3,2])
print [3,2,1], isIncreasing([3,2,1])

Output:

{} List empty or to short
None
[] List empty or to short
None
[1, 2, 3] True
[4, 6, 8] True
[2, 1, 2, 3] False
[1, 2, 3, 2] False
[3, 2, 1] False

Upvotes: 2

Related Questions