简体   繁体   English

如何使用递归查找列表中偶数的总和?

[英]How to find sum of even numbers in a list using recursion?

def sum_evens_2d(xss):
    i = 0
    counter = 0
    while (i < len(xss)):
        if(xss[i]%2 == 0):
            counter += xss[i]   
            i= i+1
        else:
            i = i+1
    return(counter)

I am trying to find the sum of the evens in the list xss .我试图在列表xss找到偶数的总和。 My restrictions are that I can not use sum() , but recursion only.我的限制是我不能使用sum() ,而只能使用递归。

Just tested this one out, it should work:刚刚测试了这个,它应该可以工作:

def even_sum(a):
    if not a:
        return 0
    n = 0
    if a[n] % 2 == 0:
        return even_sum(a[1:]) + a[n]
    else:
        return even_sum(a[1:])

# will output 154
print even_sum([1, 2, 3, 4, 5, 6, 7, 8, 23, 55, 45, 66, 68])

Provided code works fine.提供的代码工作正常。 So try to use sum as discribed below:所以尝试使用sum如下所述:

xss = range(5)
print sum(el for el in xss if el % 2 == 0)

if you cant use sum and must have recursion you can do:如果你不能使用sum并且必须有递归,你可以这样做:

def s(xss):
    if not xss:
        return 0 # for when the list is empty
    counter = 0 if xss[0] % 2 != 0 else xss[0]
    return counter + s(xss[1:])

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

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