0

I need a data structure to keep count of elements and then retrieve elements within a certain range of counts.

Example:

counter = RangeCounter()
for el in [1, 1, 2, 2, 2, 0]
    counter.add(el)

counter.get(occurence >= 1 and occurence <= 2)
>>> 1, 2 (element 1 is encountered 2 times)
>>> 2, 3 (element 2 in encountered 3 times)
Akim Akimov
  • 41
  • 1
  • 7

1 Answers1

3

with collections.Counter you could do all that:

from collections import Counter

counter = Counter([1, 1, 2, 2, 2, 0])
# Counter({2: 3, 1: 2, 0: 1})

# occurence >= 1 and occurence <= 2
res = {item: count for item, count in counter.items() if 1 <= count <= 2}
# {1: 2, 0: 1}
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111