Overview:
- The Counter class of Collections Module in Python is the implementation of the mathematical concept Multiset.
- Unlike a Set, the Multiset can have the same elements several times (n), which is called the multiplicity of the element.
- In short, a set has its elements and its multiplicity. A Multiset of (a, b, b, c, c, c) can be represented as a-1, b-2, c-3.
- The final mapping in the above representation is nothing but a dictionary, which stores a set of key-value pairs.
- Rephrasing the definition of the Counter class, a counter class in Python is a Multiset, which is implemented as a specialization of the python dictionary class dict.
- Like the way a Python dictionary stores name value pairs, a Counter object in Python stores the elements of a Multiset and their multiplicities.
- All of the following operations result in the replacement of the latest count corresponding to the element specified.
- Creation of the counter by specifying an element and its counter multiple times.
- c = Collections.counter{“a”:10, “a”:12, “a”:14}
will make the count of “a” as 14.
- Set the count using the element
- c[“a”] = 55 – will make the count of ‘a’ as 55
- Calling update() method on a counter object in Python increases the counter of an element by the value specified.
Example1:
import collections
# Create a counter colorCount = collections.Counter({"red","blue","green"}) print("Counter Object:") print(colorCount)
# Replace the count of red by 2 colorCount["red"] = 2 print("Counter Object after replacing the red count by 2:") print(colorCount) |
Output:
Counter Object: Counter({'green': 1, 'red': 1, 'blue': 1}) Counter Object after replacing the red count by 2: Counter({'red': 2, 'green': 1, 'blue': 1}) |
Example2:
import collections
# Create a counter colorCount = collections.Counter({"red":"5","blue":"6","green":"7"}) print("Counter Object:") print(colorCount)
# Replace the count of green by 9 colorCount["green"] = 9 print("Counter Object after replacing the green count by 9:") print(colorCount)
# Increase the green count by 2 colorCount.update({"green":2}) print("Counter Object after increasing the green count by 2:") print(colorCount)
# Decrease the green count by 1 colorCount.update({"green":-1}) print("Counter Object after decreasing the green count by 1:") print(colorCount) |
Output:
Counter Object: Counter({'green': '7', 'blue': '6', 'red': '5'}) Counter Object after replacing the green count by 9: Counter({'red': '5', 'blue': '6', 'green': 9}) Counter Object after increasing the green count by 2: Counter({'red': '5', 'blue': '6', 'green': 11}) Counter Object after decreasing the green count by 1: Counter({'red': '5', 'blue': '6', 'green': 10}) |