Exercise: Frequency count
Define a function freqcount(seq) that takes a sequence seq and returns a
dictionary mapping each unique element in the sequence to its frequency of
occurrence.
def freqcount(seq):
"""Count frequencies of items in seq.
>>> freqcount(['a', 'b', 'a', 'c', 'b', 'a'])
{'a': 3, 'b': 2, 'c': 1}
>>> freqcount([1, 2, 2, 3, 1, 1, 4])
{1: 3, 2: 2, 3: 1, 4: 1}
"""
Solutions
A non-mutating solution with reduce would look like:
from functools import reduce
def update_count(fdict, item):
"""Update the frequency dictionary with the given item."""
return fdict | {item: fdict.get(item, 0) + 1}
def compute_frequencies(token_list):
"""Compute frequency distribution of tokens in the list."""
return reduce(update_count, token_list, {})
The problem with this solution is that as the update_count function updates
the dictionary by creating a new dictionary each time, it is not very efficient.
One remedy for this efficiency problem is to mutate the frequency dictionary in place:
def update_count(fdict, item):
"""Update the frequency dictionary with the given item."""
fdict[item] = fdict.get(item, 0) + 1
return fdict
def compute_frequencies(token_list):
"""Compute frequency distribution of tokens in the list."""
return reduce(update_count, token_list, {})
If we want to avoid the assignment statement in update_count, we need to
switch to a third-party library for persistent data structures that make
functional updates efficient. Here is a solution with immutables.Map:
from immutables import Map
def update_count(fdict, item):
"""Update the frequency dictionary with the given item."""
return fdict.set(item, fdict.get(item, 0) + 1)
def compute_frequencies(token_list):
"""Compute frequency distribution of tokens in the list."""
return reduce(update_count, token_list, Map())
Library
from collections import Counter
def freqcount(seq):
"""Count frequencies of items in seq.
return dict(Counter(seq))