使用递归选择偶数



这里我定义了一个函数,它接收一个列表并返回同一列表中偶数的计数。当我运行程序时,我得到的回报是"无"。

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

同样。

当前实现存在两个基本问题:

  1. cint,而ints是不可变的。如果更改c,则并不意味着递归调用中的c是"更新的",每个递归调用c的值都将为0;以及
  2. 如果第一项为偶数,则不会返回值,因此Python将在这种情况下返回None
def count_even(lst, c = 0):
if lst == []:
return c
if lst[0] % 2 == 0:
c += 1
# no else
return count_even(lst[1:], c+1)  # pass a new value for c

然而,一个更紧凑的表示是:

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

然而,请注意,线性递归通常不是一个好主意,因为调用堆栈会随着元素数量的增加而增长,因此很容易导致溢出(尤其是因为Python没有实现尾调用优化(TCO((。

你几乎做到了。只是一个简单的更正。您正在调用else块中的递归,这是不对的。你应该把它放在街区之外考虑。检查以下代码:

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 = c + 1
return c + count_even(lst[1:])

print(count_even([1,2,3,4,5,6,7,8,9]))

最新更新