2013-03-27 68 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