如何通过递归获取数字列表的总和? [英] How to get the sum of a list of numbers with recursion?

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

问题描述

我想用递归函数对数字求和,即

I want to sum numbers with a recursive function, i.e.

getSum([1, 2, 3, 4, 5]) 

应该返回 1+2+3+4+5 == 15

should return 1+2+3+4+5 == 15

我不是递归函数方面的专家,我尝试过类似的方法:

I'm not an expert in recursive functions, I've tried something like:

def getSum(piece):
    for i in piece
        suc += getSum(i)

问题是我不能遍历整数.我确信这是一项非常简单的任务,但我真的无法弄清楚.

The problem is that I can't loop through integers. I'm sure this is a quite easy task but I really can't figure it out.

推荐答案

你不需要循环.递归会为您做到这一点.

You don't need to loop. Recursion will do that for you.

def getSum(piece):
    if len(piece)==0:
        return 0
    else:
        return piece[0] + getSum(piece[1:]) 
print getSum([1, 3, 4, 2, 5])

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

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