Python uses Counter to map
Python Using Counters for Mapping When you need to group a collection by certain values and calculate the frequency, you can use optimization tools such as collections.Counter
. In functional programming, grouped data is typically processed in two steps: first sorting the original collection, then using a recursive loop to identify the starting position of each group. This involves instantiating the original data, performing an O(n log n) sort, and finally reducing each key value to obtain the cumulative value or frequency.
The following generator creates a set of binned path values:
quantized = (5 * (dist // 5) for start, stop, dist in trip)
Each distance value is divided by 5, rounded, and then multiplied by 5 to get a multiple of 5 nautical miles.
The following expression creates a mapping from distance to frequency:
from collections import Counter
Counter(quantized)
This is a stateful object. Technically, it was created using imperative object-oriented programming, but it looks like a function and conforms to the design principles of functional programming.
Print the return value of the Counter(quantized).most_common()
function. The result is as follows:
[(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 frequently occurring distance value is 30 nautical miles, the shortest path segment has four zero-mile segments, and the longest is 125 nautical miles.
Your results may differ slightly from the above because the most_common()
function sorts by frequency. Items with the same frequency may be output in any order, so the order of the five lengths below may be different.
(35.0, 5), (5.0, 5), (10.0, 5), (20.0, 5), (25.0, 5)