如何在Python中使用递归计算列表整数的总和?

Patricia Arquette
发布: 2024-10-21 12:02:33
原创
683 人浏览过

How to Calculate Sum of List Integers Using Recursion in Python?

理解 Python 中的递归:对列表整数求和

递归是一种编程技术,其中函数重复调用自身来解决问题的较小实例直到达到基本条件。在Python中,我们可以将递归应用于各种任务,包括计算列表整数的总和。

递归函数:listSum

定义一个接受列表的递归函数listSum的整数并返回它们的总和,我们可以将问题分解如下:

  • 基本条件:如果列表为空(list == []),则总和为0.
  • 递归步骤:如果列表不为空,则总和为第一个元素(list[0])加上其余元素的总和(listSum(list[1: ])).

简单版:

<code class="python">def listSum(ls):
    # Base condition
    if not ls:
        return 0

    # First element + result of calling `listsum` with rest of the elements
    return ls[0] + listSum(ls[1:])</code>
登录后复制

尾调用递归:

提高效率,我们可以将当前总和传递给函数参数:

<code class="python">def listSum(ls, result):
    # Base condition
    if not ls:
        return result

    # Call with next index and add the current element to result
    return listSum(ls[1:], result + ls[0])</code>
登录后复制

传递索引版本:

为了避免创建中间列表,我们可以传递当前元素:

<code class="python">def listSum(ls, index, result):
    # Base condition
    if index == len(ls):
        return result

    # Call with next index and add the current element to result
    return listSum(ls, index + 1, result + ls[index])</code>
登录后复制

内部函数版本:

为了简化代码,我们可以定义一个递归内部函数:

<code class="python">def listSum(ls):

    def recursion(index, result):
        # Base condition
        if index == len(ls):
            return result

        # Call with next index and add the current element to result
        return recursion(index + 1, result + ls[index])

    return recursion(0, 0)</code>
登录后复制

默认参数版本:

使用默认参数,我们可以进一步简化:

<code class="python">def listSum(ls, index=0, result=0):
    # Base condition
    if index == len(ls):
        return result

    # Call with next index and add the current element to result
    return listSum(ls, index + 1, result + ls[index])</code>
登录后复制

以上是如何在Python中使用递归计算列表整数的总和?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!