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

心不动则不痛 提交于 2020-02-23 05:46:07

问题


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. My restrictions are that I can not use sum(), but recursion only.


回答1:


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



回答2:


Provided code works fine. So try to use sum as discribed below:

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



回答3:


if you cant use sum and must have recursion you can do:

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


来源:https://stackoverflow.com/questions/32936351/how-to-find-sum-of-even-numbers-in-a-list-using-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!