Chapter 4
The problem we'll have using Python is that the output generator in the trip
variable can only be used once. We can't easily perform several reductions of this
detailed data. We can use itertools.tee() to work with the iterable several times.
It seems wasteful, however, to read and parse the KML file for each reduction.
We can make our processing more efficient by materializing intermediate results.
We'll look at this in the next section. Then, we can see how to compute multiple
reductions of the available data.
Using any() and all() as reductions
The any() and all() functions provide boolean reduction capabilities. Both functions
reduce a collection of values to a single True or False. The all() function assures that
all values are True. The any() function assures that at least one value is True.
These functions are closely related to a universal quantifier and an existential
quantifier used to express mathematical logic. We might, for example, want to assert
that all elements in a given collection have some property. One formalism for this
might look like following:
(∀∈x SomeSet)Prime()x
We'd read this as: for all x in SomeSet, the function Prime x() is true. We've put a
quantifier in front of the logical expression.
In Python, we switch the order of the items slightly to transcribe the logic expression
as follows:
all(isprime(x) for x in someset)
This will evaluate each argument value (isprime(x)) and reduce the collection
of values to a single True or False.
The any() function is related to the existential quantifier. If we want to assert that
no value in a collection is prime, we might have something like one of the two
equivalent expressions:
¬∀( x∈SomeSet)Prime()xx≡(∃∈SomeSet)¬Prime()x
The first states that it is not the case that all elements in SomeSet are prime. The second
version asserts that there exists one element in SomeSet that is not prime. These two are
equivalent—that is, if not all elements are prime, then one element must be non-prime.