Functional Python Programming

(Wang) #1
Chapter 5

They also do something more sophisticated. Let's say we have our trip data from the
examples in Chapter 4, Working with Collections. We have a function that will generate
a sequence of tuples that looks as follows:


(((37.54901619777347, -76.33029518659048), (37.840832, -76.273834),
17.7246), ((37.840832, -76.273834), (38.331501, -76.459503),
30.7382), ((38.331501, -76.459503), (38.845501, -76.537331),
31.0756), ((36.843334, -76.298668), (37.549, -76.331169), 42.3962),
((37.549, -76.331169), (38.330166, -76.458504), 47.2866),
((38.330166, -76.458504), (38.976334, -76.473503), 38.8019))


Each tuple has three values: a starting location, an ending location, and a distance.
The locations are given in latitude and longitude pairs. The East latitude is positive,
so these are points along the US East Coast, about 76° West. The distances are in
nautical miles.


We have three ways of getting the maximum and minimum distances from this
sequence of values. They are as follows:



  • Extract the distance with a generator function. This will give us only the
    distances, as we've discarded the other two attributes of each leg. This won't
    work out well if we have any additional processing requirements.

  • Use the unwrap(process(wrap())) pattern. This will give us the legs
    with the longest and shortest distances. From these, we can extract just the
    distance, if that's all that's needed. The other two will give us the leg that
    contains the maximum and minimum distances.

  • Use the max() and min() functions as higher-order functions.


To provide context, we'll show the first two solutions. The following is a script
that builds the trip and then uses the first two approaches to locate the longest
and shortest distances traveled:


from ch02_ex3 import float_from_pair, lat_lon_kml, limits,
haversine, legs
path= float_from_pair(lat_lon_kml())
trip= tuple((start, end, round(haversine(start, end),4))
for start,end in legs(iter(path)))


This section creates the trip object as a tuple based on haversine distances of each
leg built from a path read from a KML file.


Once we have the trip object, we can extract distances and compute the maximum
and minimum of those distances. The code looks as follows:


long, short = max(dist for start,end,dist in trip),
min(dist for start,end,dist in trip)


print(long, short)

Free download pdf