Skip to main content
 首页 » 编程设计

python之使用递归选择偶数

2025年05月04日10jiqing9006

我在这里定义了一个函数,它接受一个列表并返回同一列表中偶数的计数。当我运行该程序时,我没有得到任何返回。

def count_even(lst, c = 0): 
    """ 
    parameters : a lst of type list 
    returns : the even elements from that list 
    """ 
    if lst == []: 
        return c 
    if lst[0] % 2 == 0: 
        c += 1 
    else: 
        return count_even(lst[1:]) 
 
 
print(count_even([1,2,3,4,5,6,7,8,9])) 

我的问题在哪里?

请您参考如下方法:

在 lst[0] % 2 == 0 的情况下,您不会返回任何内容(因此隐式返回 None)。您也永远不会在递归中包含 c 的更新值。将其更改为

if lst == []: 
    return c 
 
if lst[0] % 2 == 0: 
    c += 1 
 
return count_even(lst[1:], c) 

你很好。由于其他答案包括一些漂亮的替代解决方案,我将继续提名

def count_even(lst): 
    return 1 - lst[0]%2 + count_even(lst[1:]) if lst else 0 

还有。