Add and subtract counters

EasyCollections Programs · 4 of 20

Write a Python program that combines two inventories with Counter arithmetic.

Advertisement
Output
Counter({'pen': 6, 'book': 5})
Counter({'pen': 10, 'book': 8, 'bag': 2})

Approach

  1. + adds counts; - subtracts and drops counts below 1.

Solution

Python
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.

More collections programs

← All 20 Collections Programs

Leave a Comment