简体   繁体   English

递归列表无类型返回

[英]Recursion List None Type Returned

def largestNumber(numberList):

    if len(numberList) == 1:
        return numberList[0]
    else:
        largestNumber(numberList[1:])

For this code I am passing in a list, [1,2,3,4,5,6,7,8,9,10] , and the function returns None ... but I am expecting it to call itself until it returns 1 . 对于此代码,我传入一个列表[1,2,3,4,5,6,7,8,9,10] ,并且该函数返回None ,但是我希望它可以自行调用直到它返回1 Can someone help explain? 有人可以帮忙解释一下吗?

Remove the last element in each recursion call, and don't forget return the recursion: 删除每个递归调用中的最后一个元素,不要忘了返回递归:

def largestNumber(numberList):

    if len(numberList) == 1:
        return numberList[0]
    else:
        numberList = numberList[:-1]
        return largestNumber(numberList)

ls = [1,2,3,4,5,6,7,8,9,10]


print(largestNumber(ls))
print(ls)

=> 1
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Something seems to have gone awry in both this question and the accepted answer. 这个问题和已接受的答案似乎都出现了问题。 I'm going to try to make sense of it. 我将尽力弄清这一点。 No one would write a recursive function just to find the first or last element of a list, and certainly wouldn't name that function largestNumber() . 没有人会写一个递归函数只是为了找到列表的第一个或最后一个元素,当然也不会为那个函数largestNumber()

Let's assume the original problem specification was something like: 假设原始问题规范如下所示:

Without using max() , write a recursive function that emulates max() by finding the largest number in a list of numbers. 在不使用max() ,编写一个通过在数字列表中找到最大的数字来模拟max()的递归函数。 Called largestNumber() , it takes a list and returns a number. 称为largestNumber() ,它获取一个列表并返回一个数字。

Once the missing return is added, the remaining problem with the OP's code, and that of the currently accepted answer, is they throw away elements of the list and simply return the base case of the recursion. 一旦添加了缺失的return值,OP的代码以及当前接受的答案所剩下的问题就是它们丢弃了列表中的元素,而只是返回了递归的基本情况。 They never compare the current (first) element of the list with the result of the recursion to determine the largest number: 他们从不将列表的当前(第一个)元素与递归的结果相比较以确定最大数量:

def largestNumber(numberList):

    a, *rest = numberList

    if not rest:
        return a

    b = largestNumber(rest)

    return a if a > b else b

if __name__ == "__main__":

    import random

    my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    random.shuffle(my_list)

    print(my_list, '->', largestNumber(my_list))

TEST 测试

> python3 test.py
[2, 4, 6, 3, 5, 7, 8, 1, 9, 10] -> 10
> python3 test.py
[6, 4, 9, 1, 10, 7, 5, 3, 8, 2] -> 10
> python3 test.py
[10, 8, 7, 3, 2, 9, 1, 6, 4, 5] -> 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM