Pythonで再帰を使用してリスト整数の合計を計算する方法?

Patricia Arquette
リリース: 2024-10-21 12:02:33
オリジナル
684 人が閲覧しました

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!