Python の再帰: 理解するためのガイド
整数のリストを合計するための再帰関数
という再帰関数を作成する必要があるとします。リスト内のすべての整数の合計を計算する「listSum」。目標は、組み込み関数を使用せずにこれを行うことです。まず、関数の結果をそれ自体で表現する方法を考えます。
この場合、同じ関数を呼び出した結果に最初の数値を加算することで結果を取得できます。リスト内の残りの要素。再帰的に、これは次のように表現できます:
listSum([1, 3, 4, 5, 6]) = 1 + listSum([3, 4, 5, 6]) = 1 + (3 + listSum([4, 5, 6])) = 1 + (3 + (4 + listSum([5, 6]))) = 1 + (3 + (4 + (5 + listSum([6])))) = 1 + (3 + (4 + (5 + (6 + listSum([])))))
再帰の基本ケースは、リストが空になるとき、つまり結果 0 を必要とするイベントです。このアプローチを Python コードで実装します:
<code class="python">def listSum(ls): if not ls: return 0 return ls[0] + listSum(ls[1:])</code>
末尾呼び出し再帰
以前の実装は、実際の結果を計算するために前の関数呼び出しの値に依存しています。これは、末尾呼び出し再帰を使用して改善できます。
<code class="python">def listSum(ls, result): if not ls: return result return listSum(ls[1:], result + ls[0])</code>
追加のパラメーター結果を導入することで、その中に合計が蓄積され、基本条件が満たされたときにそれが返されます。
Passing Around Index
複数の中間リストの作成を避けるために、処理対象の項目のインデックスを渡すことができます。
<code class="python">def listSum(ls, index, result): if index == len(ls): return result return listSum(ls, index + 1, result + ls[index])</code>
基本条件は、インデックスがリストの長さに達したかどうかをチェックします。
内部関数のバージョン
パラメータの受け渡しを簡略化するために、内部関数を使用できます。
<code class="python">def listSum(ls): def recursion(index, result): if index == len(ls): return result return recursion(index + 1, result + ls[index]) return recursion(0, 0)</code>
内部関数の再帰はインデックスと結果のパラメータを受け取り、listSum が返します。初期値を使用して内部関数を呼び出した結果。
デフォルト パラメータのバージョン
デフォルト パラメータを使用すると、さらに簡素化されます。
<code class="python">def listSum(ls, index=0, result=0): if index == len(ls): return result return listSum(ls, index + 1, result + ls[index])</code>
デフォルト値はインデックスと
再帰累乗問題
累乗(基数, 指数)を計算する問題を考えてみましょう。これは、基数を指数で累乗した値を返します。再帰的に、解を定義できます:
power(2, 5) = 2 * power(2, 4) = 2 * (2 * power(2, 3)) = 2 * (2 * (2 * power(2, 2))) = 2 * (2 * (2 * (2 * power(2, 1))))
基本条件は指数が 1 以下になるときです。この場合、結果は基本そのものになります:
= 2 * (2 * (2 * (2 * 2))) = 2 * (2 * (2 * 4)) = 2 * (2 * 8) = 2 * 16 = 32
Python での実装:
<code class="python">def power(base, exponent): if exponent <p>テールコール最適化バージョンのデフォルトパラメータの使用:</p> <pre class="brush:php;toolbar:false"><code class="python">def power(base, exponent, result=1): if exponent </code>
以上がPython で効率的な合計を行うために末尾呼び出し再帰を実装するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

heouttemptemptostoreavure ofthewrongdatatypeinapythonarray、yure counteractypeerror.thisduetothearraymodule'sstricttypeeencultionyを使用します

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

theScriptisrunningwithwrongthonversionduetorectRectDefaultEntertersettings.tofixthis:1)CheckthedededefaultHaulthonsionsingpython - versionorpython3-- version.2)usevirtualenvironmentsbycreatingonewiththon3.9-mvenvmyenv、andverixe

PythonArraysSupportVariousoperations:1)SlicingExtractsSubsets、2)Appending/ExtendingAdddesements、3)inSertingSelementSatspecificpositions、4)remvingingDeletesements、5)sorting/verversingsorder、and6)listenionsionsionsionsionscreatenewlistsebasedexistin

numpyarraysAressertialentionsionceivationsefirication-efficientnumericalcomputations andDatamanipulation.theyarecrucialindatascience、mashineelearning、物理学、エンジニアリング、および促進可能性への適用性、scaledatiencyを効率的に、forexample、infinancialanalyyy

UseanArray.ArrayOverAlistinPythonは、Performance-criticalCode.1)homogeneousdata:araysavememorywithpedelements.2)Performance-criticalcode:Araysofterbetterbetterfornumerumerumericaleperations.3)interf

いいえ、notallistoperationSaresuptedbyarrays、andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorintorintorinsertizizing、whosimpactsporformance.2)リスト


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

Safe Exam Browser
Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

メモ帳++7.3.1
使いやすく無料のコードエディター

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

SublimeText3 中国語版
中国語版、とても使いやすい

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

ホットトピック









