在这里,我定义了一个函数,它接受一个列表并返回同一列表中偶数的计数.当我运行程序时,我得到无回报.
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]))
Run Code Online (Sandbox Code Playgroud)
我的问题在哪里?
如果lst[0] % 2 == 0你没有返回任何东西(因此隐式返回None).您也永远不会c在递归中包含更新的值.改为
if lst == []:
return c
if lst[0] % 2 == 0:
c += 1
return count_even(lst[1:], c)
Run Code Online (Sandbox Code Playgroud)
而且你很好.由于其他答案包括一些漂亮的替代解决方案,我将继续并提名
def count_even(lst):
return 1 - lst[0]%2 + count_even(lst[1:]) if lst else 0
Run Code Online (Sandbox Code Playgroud)
同样.