`Counter` frequencies and multiset operations [ref]
Problem
- Count
[1, 2, 2, 3] and read the missing count for 9.
- Find the two most common values in
["a", "b", "a", "c", "a", "b"].
- Intersect the multisets
[1, 2, 2, 3] and [2, 2, 2, 4], then expand their intersection.
- Decrement
"a" in the counts for "aab", then delete that entry.
- Compare the character counts of
"ab" and "ba".
Python solution
from collections import Counter
counts = Counter([1, 2, 2, 3])
counts # Counter({2: 2, 1: 1, 3: 1})
counts[9] # 0
Counter(["a", "b", "a", "c", "a", "b"]).most_common(2)
# [('a', 3), ('b', 2)]
common = Counter([1, 2, 2, 3]) & Counter([2, 2, 2, 4])
common # Counter({2: 2})
list(common.elements()) # [2, 2]
counts = Counter("aab")
counts["a"] -= 1
counts # Counter({'a': 1, 'b': 1})
del counts["a"]
counts # Counter({'b': 1})
Counter("ab") == Counter("ba") # True
Links