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