首頁  >  文章  >  後端開發  >  如何在Python中使用遞歸計算列表整數的總和?

如何在Python中使用遞歸計算列表整數的總和?

Patricia Arquette
Patricia Arquette原創
2024-10-21 12:02:33685瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn