Skip to content

Instantly share code, notes, and snippets.

@hjwp
Last active October 17, 2023 10:25
Show Gist options
  • Save hjwp/9ea413199e2b90553354af8caa9935a8 to your computer and use it in GitHub Desktop.
Save hjwp/9ea413199e2b90553354af8caa9935a8 to your computer and use it in GitHub Desktop.
reduce vs non-reduce versions of Counter / frequencies
"""
finding use cases for "reduce" in python, attempt #2.
"reimplementing Counter()
cf https://docs.python.org/3/library/collections.html#collections.Counter
cf https://clojuredocs.org/clojure.core/frequencies
"""
import functools
import typing
things = ["red", "blue", "red", "green", "blue", "blue"]
expected = {"red": 2, "blue": 3, "green": 1}
T = typing.TypeVar("T")
def counter_pythonic(l: list[T]) -> dict[T, int]:
# um, this may be O(n²) 😅
return {thing: l.count(thing) for thing in set(l)}
def counter_reduce(l: list[T]) -> dict[T, int]:
return functools.reduce(
lambda acc, x: acc | {x: acc.get(x, 0) + 1},
l,
{},
)
def test_it_works_pythonic():
assert counter_pythonic(things) == expected
def test_it_works_pythonic():
assert counter_reduce(things) == expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment