Functional Python Programming

(Wang) #1
Chapter 5

filterfalse() as variations on this theme. Refer to Chapter 8, The Itertools Module to
understand the usage of the itertools module's filterfalse() function.


We might apply this to our trip data to create a subset of legs that are over 50
nautical miles long, as follows:


long= list(filter(lambda leg: dist(leg) >= 50, trip)))


The predicate lambda will be True for long legs, which will be passed. Short legs will
be rejected. The output is the 14 legs that pass this distance test.


This kind of processing clearly segregates the filter rule (lambda leg: dist(leg)



= 50) from any other processing that creates the trip object or analyzes the
long legs.



For another simple example, look at the following code snippet:





filter(lambda x: x%3==0 or x%5==0, range(10))





<filter object at 0x101d5de50>





sum(_)





23


We've defined a simple lambda to check whether a number is a multiple of three or a
multiple of five. We've applied that function to an iterable, range(10). The result is
an iterable sequence of numbers that are passed by the decision rule.


The numbers for which the lambda is True are [0, 3, 5, 6, 9], so these values are
passed. As the lambda is False for all other numbers, they are rejected.


This can also be done with a generator expression by executing the following code:





list(x for x in range(10) if x%3==0 or x%5==0)





[0, 3, 5, 6, 9]


We can formalize this using the following set comprehension notation:


{xx|0≤<^10 ∧=(x ()mod3 0 m∨=x ()od5 0)}

This says that we're building a collection of x values such that x is in range(10) and
x%3==0 or x%5==0. There's a very elegant symmetry between the filter() function
and formal mathematical set comprehensions.

Free download pdf