# Python Example – Write a Python program to perform Counter arithmetic and set operations for aggregating results # (Python Example for Citizen Data Scientist & Business Analyst)

Write a Python program to perform Counter arithmetic and set operations for aggregating results.

Sample Solution:

Python Code:

``````
import collections

c1 = collections.Counter([1, 2, 3, 4, 5])
c2 = collections.Counter([4, 5, 6, 7, 8])

print('C1:', c1)
print('C2:', c2)
print('nCombined counts:')
print(c1 + c2)
print('nSubtraction:')
print(c1 - c2)
print('nIntersection (taking positive minimums):')
print(c1 & c2)
print('nUnion (taking maximums):')
print(c1 | c2)
``````

Sample Output:

```C1: Counter({1: 1, 2: 1, 3: 1, 4: 1, 5: 1})
C2: Counter({4: 1, 5: 1, 6: 1, 7: 1, 8: 1})

Combined counts:
Counter({4: 2, 5: 2, 1: 1, 2: 1, 3: 1, 6: 1, 7: 1, 8: 1})

Subtraction:
Counter({1: 1, 2: 1, 3: 1})

Intersection (taking positive minimums):
Counter({4: 1, 5: 1})

Union (taking maximums):
Counter({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1})```

## Write a Python program to perform Counter arithmetic and set operations for aggregating results

#### Free Machine Learning & Data Science Coding Tutorials in Python & R for Beginners. Subscribe @ Western Australian Center for Applied Machine Learning & Data Science. ```