如何在索引超出范围之前停止递归函数?

时间:2015-05-14 09:15:48

标签: python-2.7

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

我这是为了检查列表是否已排序。当没有更多要检查时,如何使功能停止?

我得到了错误

  

“列表索引超出范围”。

1 个答案:

答案 0 :(得分:2)

只需添加:

  • 检查列表中是否只有两个元素
  • 检查列表中是否只有一个元素或没有元素

代码:

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

输出:

{} 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