This function is used to apply some two-argument function
pairwise to each pair of the elements of a sequence f(x, y) in turn, with an
optional initial value S. Here are the general forms:
I
reduce(f,S) reduce(f,S,I)
The result depends on the number of elements in , and whether the
initial value S is
supplied. Let's look first at the case where argument I is not supplied.
I
If has only
one element, the result is S.
S[0]
If has two
elements, the result is S.
f(S[0],
S[1])
If has three
elements, the result is S.
f(f(S[0], S[1]), S[2])
If has four
or more elements, S is applied first to f and S[0], then to that result and
S[1], and so
on until all elements are reduced to a single value.
S[2]
If an initial value is provided, the result is the same as Ireduce(.
f, [I]+list(S))
Some examples:
>>> def x100y(x,y): ... return x*100+y ... >>> reduce(x100y, [15]) 15 >>> reduce(x100y, [1,2]) 102 >>> reduce(x100y, [1,2,3]) 10203 >>> reduce(x100y, (), 44) 44 >>> reduce(x100y, [1], 2) 201 >>> reduce(x100y, [1,2], 3) 30102 >>> reduce(x100y, [1,2,3], 4) 4010203