编写一个递归函数来查找列表中有多少个元素大于 30

Writing a recursive function to find how many elements in list are greater than 30

我想编写一个名为 greater_than_30(list_nums) 递归 函数,它可以找出给定列表中有多少数字大于 30。

例如:

list1 = [10, 35, 30, 50]
output - 2

这是我编写的函数:

def greater_than_30(list_nums):
    if len(list_nums) == 1:
        if list_nums[0] > 30:
            return 1
            
    else:
        if list_nums[0] > greater_than_30(list_nums[1:]):
            return list_nums[0] 
        else:
            return greater_than_30(list_nums[1:])


>>>a_list = [13, 21, 50, 34, 29, 33]
print(greater_than_30(a_list))
3 #output expected
50 #output gotten

你实际上从来没有在那里数过它。如果你更换

if list_nums[0] > greater_than_30(list_nums[1:]):
    return list_nums[0]

if list_nums[0] > 30:
    return 1 + greater_than_30(list_nums[1:])

它将按预期工作。

def grater_than_30(my_list, count=0):
    if len(my_list) == 0:
        return count
    if my_list[0] > 30:
        count += 1
    count = grater_than_30(my_list[1:], count)
    return count


list1 = [13, 21, 50, 34, 29, 33]
grater_than_30(list1)

虽然我不明白你为什么要递归地做这个微不足道的操作,但这里有一个解决方案:

list1 = [13, 21, 50, 34, 29, 33]

def greater_than_30(lst):
    if len(lst) == 0:
        return 0
    return (1 if lst[0] > 30 else 0) + greater_than_30(lst[1:])

print(greater_than_30(list1))

输出:

3