Functional Python Programming

(Wang) #1
Chapter 8

The first Leg function is a short trip between two points on the Chesapeake Bay.


We can add a function that will build a more complex tuple with the input order
information as part of the tuple. First, we'll define a slightly more complex version
of the Leg class:


Leg = namedtuple("Leg", ("order", "start", "end", "distance"))


This is similar to the Leg instance shown in Chapter 7, Additional Tuple Techniques
but it includes the order as well as the other attributes. We'll define a function that
decomposes pairs and creates Leg instances as follows:


def ordered_leg_iter(pair_iter):
for order, pair in enumerate(pair_iter):
start, end = pair
yield Leg(order, start, end, round(haversine(start, end),4))


We can use this function to enumerate each pair of starting and ending points.
We'll decompose the pair and then reassemble the order, start, and end parameters
and the haversine(start,end) parameter's value as a single Leg instance. This
generator function will work with an iterable sequence of pairs.


In the context of the preceding explanation, it is used as follows:


with urllib.request.urlopen("file:./Winter%202012-2013.kml") as
source:


path_iter = float_lat_lon(row_iter_kml(source))
pair_iter = legs(path_iter)
trip_iter = ordered_leg_iter(pair_iter)
trip= tuple(trip_iter)


We've parsed the original file into the path points, created start-end pairs, and then
created a trip that was built of individual Leg objects. The enumerate() function
assures that each item in the iterable sequence is given a unique number that
increments from the default starting value of 0. A second argument value can be
given to provide an alternate starting value.


Running totals with accumulate()


The accumulate() function folds a given function into an iterable, accumulating
a series of reductions. This will iterate over the running totals from another
iterator; the default function is operator.add(). We can provide alternative
functions to change the essential behavior from sum to product. The Python library
documentation shows a particularly clever use of the max() function to create a
sequence of maximum values so far.

Free download pdf