Functional Python Programming

(Wang) #1

Higher-order Functions


We've used a generator function to extract the relevant item from each leg of the
trip tuple. We've had to repeat the generator function because each generator
expression can be consumed only once.


The following are the results:


129.7748 0.1731


The following is a version with the unwrap(process(wrap())) pattern. We've
actually declared functions with the names wrap() and unwrap() to make it clear
how this pattern works:


def wrap(leg_iter):


return ((leg[2],leg) for leg in leg_iter)


def unwrap(dist_leg):


distance, leg = dist_leg


return leg


long, short = unwrap(max(wrap(trip))), unwrap(min(wrap(trip)))


print(long, short)


Unlike the previous version, this locates all attributes of the legs with the longest
and shortest distances. Rather than simply extracting the distances, we put the
distances first in each wrapped tuple. We can then use the default forms of the min()
and max() functions to process the two tuples that contain the distance and leg
details. After processing, we can strip the first element, leaving just the leg details.


The results look as follows:


((27.154167, -80.195663), (29.195168, -81.002998), 129.7748)


((35.505665, -76.653664), (35.508335, -76.654999), 0.1731)


The final and most important form uses the higher-order function feature of the
max() and min() functions. We'll define a helper function first and then use it to
reduce the collection of legs to the desired summaries by executing the following
code snippet:


def by_dist(leg):


lat, lon, dist= leg


return dist


long, short = max(trip, key=by_dist), min(trip, key=by_dist)


print(long, short)

Free download pdf