Functional Python Programming

(Wang) #1
Chapter 4

We can demonstrate that Python follows these rules:





all(())
True
any(())
False





Python gives us some very nice tools to perform processing that involves logic.
We have the built-in and, or, and not operators. However, we also have these
collection-oriented any() and all() functions.


Using len() and sum()


The len() and sum() functions provide two simple reductions: a count of the
elements and the sum of the elements in a sequence. These two functions are
mathematically similar, but their Python implementation is quite different.


Mathematically, we can observe this cool parallelism. The len() function returns


the sum of 1's for each value in a collection, X:∑∑xX∈ 1 = xX∈ x^0.

The sum() function returns the sum of x for each value in a collection, X:
1


∑∑xX∈ xx= xX∈.


The sum() function works for any iterable. The len() function doesn't apply to
iterables; it only applies to sequences. This little asymmetry in the implementation
of these functions is a little awkward around the edges of statistical algorithms.


For empty sequences, both of these functions return a proper additive identity
element of 0.





sum(())
0





Of course, sum(()) returns an integer 0. When other numeric types are used,
the integer 0 will be coerced to the proper type for the available data.

Free download pdf