reduce
function (http://docs.python.org/3/library/functools.html?highlight=reduce#functools.reduce).
Note that this is Python's equivalent of the abstract fold
function that you saw in CPSC 110.It's important to note that the first argument passed to thefunctools.reduce(function, sequence[, initializer])
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. Suppose we define the following function:
def sub(a, b):
"""
int, int -> int
Produces the difference of a and b
>>> sub(3, 4)
-1
"""
return a - b
Then the following call to reduce:
reduce(sub, [1, 2, 3, 4])
is the equivalent ofsub(sub(sub(1, 2), 3), 4)
.
If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.
reduce
function is itself a function!sub
function above: