值在函数中正确打印,但返回时为None

时间:2013-03-27 02:05:11

标签: python list function recursion return

我只是试图刷新我的python,所以我确信我在这里犯了一个基本错误。我的代码只是一个玩具应用程序,可以找到循环排序数组中的最大项目。

这是我的代码:

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时?

1 个答案:

答案 0 :(得分: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)