2013-03-27 57 views
2

我只是想刷上我的蟒蛇,所以我相信我在這裏犯了一個基本的錯誤。我的代碼只是一個玩具應用程序,它可以在循環排序的數組中找到最大的項目。值打印功能正確,但返回時是None

這裏是我的代碼:

def listIsSorted(l): 
    if l[0] < l[-1]: 
     return 1 
    return 0 

def findLargest(l): 
    listLength = len(l) 
    if(listLength == 1): 
     return l[0] 
    if(listLength == 2): 
     if(l[0] > l[1]): 
      print("OMG I Found it: " + str(l[0])) 
      return l[0] 
     return l[1] 

    halfway = int(listLength/2) 
    firsthalf = l[:int(halfway)] 
    secondhalf = l[int(halfway):] 
    if(listIsSorted(firsthalf) and listIsSorted(secondhalf)): 
     return max(l[halfway - 1], l[-1]) 
    elif (listIsSorted(firsthalf)): 
     findLargest(secondhalf) 
    else: 
     findLargest(firsthalf) 

l4 = [5,1,2,3] 
print(findLargest(l4)) 

這個輸出以下:

OMG I Found it: 5 
None 

我的問題是:爲什麼會被返回爲None類型,當它剛剛打印爲5?

+0

Soo..What是問題嗎? – Sinkingpoint 2013-03-27 02:07:48

+0

用明確的問題編輯 – PFranchise 2013-03-27 02:09:11

回答

1

我猜測它必須修改這種方式,因爲你忘記返回遞歸調用的結果:

def findLargest(l): 
    listLength = len(l) 
    if listLength == 1: 
     return l[0] 
    if listLength == 2: 
     if l[0] > l[1]: 
      print "OMG I Found it: {0}".format(l[0]) 
      return l[0] 
     return l[1] 

    halfway = int(listLength/2) 
    firsthalf = l[:int(halfway)] 
    secondhalf = l[int(halfway):] 
    if listIsSorted(firsthalf) and listIsSorted(secondhalf): 
     return max(l[halfway - 1], l[-1]) 
    elif listIsSorted(firsthalf): 
     return findLargest(secondhalf) 
    else: 
     return findLargest(firsthalf) 
+0

呵呵。接得好。欣賞第二雙眼睛。祝你有個好的一天! – PFranchise 2013-03-27 02:10:42

+0

@PFranchise歡迎您 – 2013-03-27 02:11:03