Functional Python Programming

(Wang) #1

Recursions and Reductions


If we print Counter(quantized).most_common() function, we'll see the
following results:


[(30.0, 15), (15.0, 9), (35.0, 5), (5.0, 5), (10.0, 5), (20.0, 5),
(25.0, 5), (0.0, 4), (40.0, 3), (45.0, 3), (50.0, 3), (60.0, 3),
(70.0, 2), (65.0, 1), (80.0, 1), (115.0, 1), (85.0, 1), (55.0, 1),
(125.0, 1)]


The most common distance was about 30 nautical miles. The shortest recorded leg
was four instances of 0. The longest leg was 125 nautical miles.


Note that your output may vary slightly from this. The results of the most_common()
function are in order by frequency; equal-frequency bins may be in any order.
These 5 lengths may not always be in the order shown:


(35.0, 5), (5.0, 5), (10.0, 5), (20.0, 5), (25.0, 5)


Building a mapping by sorting


If we want to implement this without using the Counter class, we can use a more
functional approach of sorting and grouping. Following is a common algorithm:


def group_sort(trip):


def group(data):


previous, count = None, 0


for d in sorted(data):


if d == previous:


count += 1


elif previous is not None: # and d != previous


yield previous, count


previous, count = d, 1


elif previous is None:


previous, count = d, 1


else:


raise Exception("Bad bad design problem.")


yield previous, count


quantized= (5*(dist//5) for start,stop,dist in trip)


return dict(group(quantized))

Free download pdf