python 2.7 - How to stop recursive function before index out of range? -
def isincreasing(ls): if not ls: print "list empty or short" return return (false if ls[0] > ls[1] else isincreasing(ls[1:]))
i have made check if list sorted. how can make function stop when there no more check?
im getting error
"list index out of range".
just add:
- checking if 2 elements in list
- checking if 1 element or no element in list
code:
def isincreasing(ls): if len(ls) < 2: print "list empty or 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 short none [] list empty or short none [1, 2, 3] true [4, 6, 8] true [2, 1, 2, 3] false [1, 2, 3, 2] false [3, 2, 1] false
Comments
Post a Comment