2015-05-14 29 views
1
def isIncreasing(ls): 
if not ls: 
    print "List empty or to short" 
    return 
return (False if ls[0] > ls[1] else isIncreasing(ls[1:])) 

我已經做了這個檢查列表是否排序。當沒有更多的檢查時,我該如何使功能停止?如何在索引超出範圍之前停止遞歸函數?

即時得到錯誤

「列表索引超出範圍」。

回答

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 
+0

非常感謝!現在我正在掌握這種遞歸的編程方式! :) –