Python Counter

System design interview questions can be so open-ended, that it's too hard to know the right way to prepare. Now I am able to crack the design rounds of Amazon, Microsoft, and Adobe after buying this book. Daily revise one design question and I promise you can crack the design round.

What is a Python Counter?

Python counter is a container present in the collections module. It holds the count of each element present in the container.

A container can be defined as an object which in turn holds objects. You can access the objects by iterating over them. List, Tuple, and Dictionary are examples of built-in containers. Counters are an alternatives to built-in containers.

The Python dictionary is a superclass of the Python Counter. Hence like a dictionary, the counter is also an unordered collection. In counter, the elements and their respective count are stored as a key-value pair in dictionary format.  It’s similar to multisets in other languages.

Initializing the Python counter:

We can call the counter construction in three ways, with:

  • a sequence of items like list, tuple, strings, etc.,
  • a dictionary containing keys and their respective count values.
  • keyword argument mapping the string names to their respective count values.
from collections import Counter

#sequence of items
print(Counter(('A','1','2','3','A','A','3','A')))

#dictionary containing keys and their respective counts
print(Counter({'A':1,'B':3,'C':7}))

#keyword arguments mapping keys to count values
print(Counter(A=1,B=3,C=7))

The output is:

Counter({'A': 4, '3': 2, '1': 1, '2': 1})
Counter({'C': 7, 'B': 3, 'A': 1})
Counter({'C': 7, 'B': 3, 'A': 1})

Deleting elements from the Python counter:

With del keyword, we can element any element from the counter. We won’t get any error even if the given element is not present.

from collections import Counter

counter=Counter()
counter.update([1,3,2,1,4,3,2,2,3])
print(counter)
del counter[4]
print(counter)
Counter({3: 3, 2: 3, 1: 2, 4: 1})
Counter({3: 3, 2: 3, 1: 2})

Operations on Python counter:

We can perform arithmetic operations like addition, subtraction, intersection, and union on a Python counter.

  • Addition and subtraction return only the positive numbers.
  • Intersection returns the positive elements present in both counters with the minimum value.
  • Union returns the positive elements present in both counters with the maximum value.
from collections import Counter

counter=Counter()
counter1=Counter([1,3,2,1,4,3,2,2,3])
counter2=Counter((1,3,4,2,5))

#Addition
print(counter1+counter2)
#Subtraction
print(counter1-counter2)
#Intersection
print(counter1&counter2)
#union
print(counter1|counter2)
Counter({3: 4, 2: 4, 1: 3, 4: 2, 5: 1})
Counter({3: 2, 2: 2, 1: 1})
Counter({1: 1, 3: 1, 2: 1, 4: 1})
Counter({3: 3, 2: 3, 1: 2, 4: 1, 5: 1})

Get distinct elements of a sequence:

Another way we can make use of counter is to get the count of distinct elements of a collection.

from collections import Counter

sequence=[1,2,4,2,3,1,2,3,3,2,4,1]
print(Counter(sequence))
Counter({2: 4, 1: 3, 3: 3, 4: 2})

Commonly used methods on Python Counter:

elements():

elements() is a function of the Counter class. The return type is itertools hence it returns an iterator containing all known elements in the counter.

<class 'itertools.chain'>

Parameters:

It doesn’t accept any parameters.

Errors and Exceptions:

  • Since it returns an iterator, when printed directly it prints the garbage value.
counter1=Counter(A=4,B=5,C=12)

print(counter1.elements())
<itertools.chain object at 0x02DAA370>
  • The elements() return only the elements with the positive count, hence ignores the ones with zero and negative values.
from collections import Counter

sequence=Counter(a=2,d=-1,b=0,c=3)

for i in sequence.elements():
    print("% s : % s" % (i, sequence[i]))
a : 2
a : 2
c : 3
c : 3
c : 3

subtract():

Deduces elements from the counter which are present in the counter passed. Unlike elements() it returns the elements which count value zero as well as negative.

from collections import Counter 

counter1=Counter(A=4,B=5,C=12) 
counter2=Counter(A=5,B=5,C=3) 
counter1.subtract(counter2) 

print(counter1)
Counter({'C': 9, 'B': 0, 'A': -1})

update():

We can either create an empty counter or update the exiting counter using the update() method.

from collections import Counter 

#Initializing empty Counter 
counter=Counter() 
counter.update([1,3,2,1,4,3,2,2,3]) 
print(counter) 

counter.update((1,3,4,2)) 
print(counter)
Counter({3: 3, 2: 3, 1: 2, 4: 1}) 
Counter({3: 4, 2: 4, 1: 3, 4: 2})

When we update the counter, the existing data will not be replaced, it gets increased.

 

Crack System Design Interviews
Translate »