理解Python 中的遞歸:對列表整數求和
遞歸是一種程式設計技術,其中函數重複調用自身來解決問題的較小實例直到達到基本條件。在Python中,我們可以將遞歸應用於各種任務,包括計算清單整數的總和。
遞歸函數:listSum
定義一個接受列表的遞歸函數listSum的整數並傳回它們的總和,我們可以將問題分解如下:
簡單版:
<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中文網其他相關文章!