InterviewSolution
| 1. |
What are the characteristics of Counter object in Python? |
|
Answer» Counter class is defined in collections module, which is part of Python’s standard LIBRARY. It is defined as a subclass of built-in dict class. Main application of Counter object is to keep count of hashable objects. Counter object is a collection of KEY-value pairs, telling how many times a key has appeared in sequence or dictionary. The Counter() function acts as a constructor. Without arguments, an empty Counter object is returned. When a sequence is given as argument, it results in a dictionary holding occurrences of each ITEM. >>> from collections import Counter >>> c1=Counter() >>> c1 Counter() >>> c2=Counter('MALAYALAM') >>> c2 Counter({'A': 4, 'M': 2, 'L': 2, 'Y': 1}) >>> c3=Counter([34,21,43,32,12,21,43,21,12]) >>> c3 Counter({21: 3, 43: 2, 12: 2, 34: 1, 32: 1})Counter object can be created directly by giving a dict object as argument which itself should be k-v pair of element and count. >>> c4=Counter({'Ravi':4, 'Anant':3, "Rakhi":3})The Counter object supports all the methods that a built-in dict object has. One important method is elements() which returns a chain object and returns an iterator of element and value repeating as many times as value. >>> list(c4.elements()) ['Ravi', 'Ravi', 'Ravi', 'Ravi', 'Anant', 'Anant', 'Anant', 'Rakhi', 'Rakhi', 'Rakhi'] |
|