2015-10-01 51 views
0

作爲練習,我試圖使用Python中的遞歸在列表中找到最低的正數。這幾乎可以工作,找到2時print(first),但它最終返回None。有沒有辦法解決這個問題,或者我在錯誤的軌道上?遞歸Python函數在列表中查找最小數字

def find_lowest(lst): 
    """Return the lowest positive number in a list.""" 
    def lowest(first, rest): 
     # Base case 
     if len(rest) == 0: 
      print(first) # This line is only to check the value 
      return first 
     if first > rest[0] or first < 0: 
      lowest(rest[0], rest[1:]) 
     else: 
      lowest(first, rest[1:]) 
    return lowest(lst[0], lst[1:]) 

a = [6, -4, 4, 8, -127, 5, 7, 2, 3, 9] 
print(find_lowest(a)) # Prints None, but should print the lowest number 

編輯:這個問題是不完全一樣的另一種。尋找這種答案的人不會找到另一個答案,因爲它提出了類似的問題,但方式卻非常不同。堆棧溢出具有有用的內容,但敵意和低調顯得令人討厭。

+0

什麼敵意?重複看起來與我基本相同。 – showdev

+0

很多人根據標題找不到其他答案。我沒有,即使經過了一番搜索。 SO是一個令人難以置信的有用資源,但使用起來非常令人沮喪。我想我花了三年的時間才能寫出評論來幫助某人解答問題。這有點像維基百科 - 非常有用,但過於熱心適度。像這樣的網站是信息的長尾巴。有人使用其他關鍵字搜索Google會找到其他關鍵字,而使用這些關鍵字進行搜索的用戶將會找到此信息。沒有必要downvote。 SO不會耗盡磁盤空間。 – Josh

回答

2

問題是您忘記在第二個ifelse個案中添加return陳述。

下面應該工作:

def find_lowest(lst): 
    """Return the lowest positive number in a list.""" 
    def lowest(first, rest): 
     # Base case 
     if len(rest) == 0: 
      return first 
     if first > rest[0] or first < 0: 
      return lowest(rest[0], rest[1:]) 
     else: 
      return lowest(first, rest[1:]) 
    return lowest(lst[0], lst[1:]) 

a = [6, -4, 4, 8, -127, 5, 7, 2, 3, 9]