Python Practice › Collections Programs › Program 4
Add and subtract counters
Write a Python program that combines two inventories with Counter arithmetic.
Output
Counter({'pen': 6, 'book': 5})
Counter({'pen': 10, 'book': 8, 'bag': 2})Approach
+adds counts;-subtracts and drops counts below 1.
Solution
from collections import Counter stock = Counter(pen=10, book=5, bag=2)sold = Counter(pen=4, bag=2)print(stock - sold)print(stock + Counter(book=3))Output
Counter({'pen': 6, 'book': 5})
Counter({'pen': 10, 'book': 8, 'bag': 2})Learn the concept
New to this topic? Read the lesson, then come back.