Functional Python Programming

(Wang) #1

The Functools Module


Reducing sets of data with reduce()


The sum(), len(), max(), and min() functions are—in a way— all specializations
of a more general algorithm expressed by the reduce() function. The reduce()
function is a higher-order function that folds a function into each pair of items
in an iterable.


A sequence object is given as follows:


d = [2, 4, 4, 4, 5, 5, 7, 9]


The function, reduce(lambda x,y: x+y, d), will fold in + operators to the list
as follows:


2+4+4+4+5+5+7+9


Including () can show the effective grouping as follows:


((((((2+4)+4)+4)+5)+5)+7)+9


Python's standard interpretation of expressions involves a left-to-right evaluation
of operators. The fold left isn't a big change in meaning.


We can also provide an initial value as follows:


reduce(lambda x,y: x+y**2, iterable, 0)


If we don't, the initial value from the sequence is used as the initialization. Providing
an initial value is essential when there's a map() function as well as a reduce()
function. Following is how the right answer is computed with an explicit 0 initializer:


0+ 22+ 42+ 42+ 42+ 52+ 52+ 72+ 92


If we omit the initialization of 0, and the reduce() function uses the first item as an
initial value, we get the following wrong answer:


2+ 42+ 42+ 42+ 52+ 52+ 72+ 9**2


We can define a number of built-in reductions using the reduce() higher-order
function as follows:


sum2= lambda iterable: reduce(lambda x,y: x+y**2, iterable, 0)


sum= lambda iterable: reduce(lambda x, y: x+y, iterable)


count= lambda iterable: reduce(lambda x, y: x+1, iterable, 0)


min= lambda iterable: reduce(lambda x, y: x if x < y else y,
iterable)

Free download pdf