Skip to main content
 首页 » 编程设计

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

2025年05月04日10zhoujg

我只是想复习一下我的 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?

请您参考如下方法:

我想它必须这样修改,因为你忘记返回递归调用的结果:

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)