python - 使用递归选择偶数

标签 python list recursion

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

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

还有。

关于python - 使用递归选择偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53242251/

相关文章:

python : list index out of range error while iteratively popping elements

c - 返回n==0? 0 : fib2(n, 0, 1) 我找不到那个?

java - 返回树的中序字符串

c++ - 在 C++ 中通过递归反转字符串

python - 列表理解中python中的递归函数调用给出的结果与首先将调用结果分配给变量不同

python re.compile() 和 re.findall()

python - 如何将QChart坐标映射到QChartView点?

Python:ValueError:使用序列设置数组元素

r - 在列表上应用 paste0 函数

c# - 这个。和列表<T>