ソースコードの歩き方《IronPython》reduce 1/5

Previous|1/5|Next
Python.use(better, src=”IronPython”) # ソースコードを散策する記事一覧

組み込み関数 reduceIronPython

《著》本間りす《監修》小泉ひよ子とタマゴ倶楽部
更新♪2008/09/09

IronPythonソースコードを読みながら、Python の環境下で、その動作を確認します。なぜ IronPython の動作を Python で確認するのか、その理由は後述します。

IDLE を起動する

Python IDLE を起動すると、次のようなプロンプトが現れます。

Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) 
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "copyright", "credits" or "license()" for more information.

****************************************************************
Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet.
****************************************************************

IDLE 1.2.2
>>> type(reduce)

これを見て、reduce が「組み込み関数」であるのが分かります。

組み込み関数 reduce

次に、組み込み関数 reduce のヘルプ情報を確認します。

>>> help(reduce)
Help on built-in function reduce in module __builtin__:

reduce(...)
reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.

これを見て、2つまたは3つの引数を与えると、値が得られるのが分かります。実際に、その動作を確認してみましょう。

事例:総和を求める

関数 reduce の典型的な利用法のひとつが、数列の総和を求めるというものです。

>>> reduce(lambda acc,e: acc+e, range(101), 0)5050

ここでは、整数 0〜100 の和を求めています。この事例は、数学の世界で偉大な足跡を残したガウスが、幼年期に「1 から 100 までの数字を足す」式を教師が黒板に書き終える前に「答えは 5050 (=101×50) になる」としたエピソードとしても有名です。
第1引数 function には(引数が2つ必要な)関数を指定します。ここでは、lambda 関数の第1引数 acc に初期値を与えると、それに続く途中経過を保持するとともに、その第2引数 e は(reduce の第2引数)range(101) の各要素を参照します。
第2引数 sequence には、任意のシーケンスを指定します。ここでは、総和を求める対象として、0 から 100 までの整数を列挙したリストを与えます。
第3引数 initial には、任意の初期値を指定します。第2引数に空シーケンスを与えると、その総和は初期値と同じ 0 になります。

>>> reduce(lambda acc,e: acc+e, range(101))5050

第3引数を省略すると、range(101) の先頭要素 0 が初期値になります。すると、((((0+1)+2)+3)+...)+100 という過程を経て、リターン値 5050 が得られます。

>>> reduce(lambda acc,e: acc+e, [], -1)-1

空リスト [] を与えると、初期値 -1 がそのまま、リターン値として得られます。


Previous|1/5|Next