简体   繁体   English

使用递归选择偶数

[英]Picking even numbers using recursion

Here I have defined a function that takes in a list and returns the count of the even numbers in that same list.When I run the program I get None in return. 在这里我定义了一个函数,该函数接受一个列表并返回同一列表中偶数的计数。当我运行该程序时,我得到None。

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]))

Where is my problem? 我的问题在哪里?

In case lst[0] % 2 == 0 , you are not returning anything (thus implicitly returning None ). 如果lst[0] % 2 == 0 ,则不返回任何内容(因此隐式返回None )。 You also never include the updated value of c in the recursion. 您也永远不会在递归中包含c的更新值。 Change that to 更改为

if lst == []:
    return c

if lst[0] % 2 == 0:
    c += 1

return count_even(lst[1:], c)

and you're good. 而且你很好。 Since the other answers include some nifty alternative solutions, I'll go ahead and nominate 由于其他答案包括一些漂亮的替代解决方案,因此我将继续提名

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

as well. 也一样

There are two basic problems with the current implementation: 当前的实现有两个基本问题:

  1. c is an int , and int s are immutable. c是一个int ,并且int是不可变的。 If you change c , this thus does not mean the c in recursive calls is "updated", each recursive call c will have as value 0 ; 如果更改c ,因此,这并不意味着c在递归调用的“更新”,每次递归调用c将具有值0 ; and
  2. you do not return a value in case the first item is even, so Python will return None in that case. 如果第一个项目为偶数,则不会返回任何值,因此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

A more compact representation is however: 但是,更紧凑的表示形式是:

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

Note however that linear recursion is typically not a good idea, since the call stack will grow with the number of elements, and thus easily result in an overflow (especially since Python does not implement tail call optimization (TCO) ). 但是请注意, 线性递归通常不是一个好主意,因为调用堆栈会随着元素数量的增长而增长,因此很容易导致溢出(尤其是因为Python未实现尾部调用优化(TCO) )。

You almost did it. 您几乎做到了。 Just a simple correction. 只是一个简单的更正。 You are calling the recursion in else block which is not right. 您在else块中调用了递归,这是不正确的。 You should consider it outside the block. 您应该在块之外考虑它。 Check the below code : 检查以下代码:

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]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM