如何使用递归查找列表中偶数的总和? [英] How to find sum of even numbers in a list using recursion?

查看:57
本文介绍了如何使用递归查找列表中偶数的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)

我试图在 xss 列表中找到偶数的总和.我的限制是我不能使用 sum(),而只能使用递归.

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.

推荐答案

刚刚测试了这个,应该可以:

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

这篇关于如何使用递归查找列表中偶数的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆