-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path22_Counter.py
More file actions
50 lines (42 loc) · 1.05 KB
/
22_Counter.py
File metadata and controls
50 lines (42 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from collections import Counter
val = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
val1 = ["a","d","g","h","i","i","a"]
print(Counter(val1))
print(Counter(val))
# Creating a Counter
ctr1 = Counter([1,1,3,3,4,6])
ctr2 = Counter({1:2,2:3,3:2})
ctr3 = Counter("hello")
print(ctr1)
print(ctr2)
print(ctr3)
# Accessing Counter Elements
ctr = Counter([1,2,2,3,3,3])
print(ctr[1]) # print count of 1
print(ctr[2]) # print count of 2
print(ctr[3]) # print count of 3
print(ctr[5]) # print count of 5 (not present, so returns 0)
# Updating counters
ctr4 = Counter([2,3,4,5,1,2])
ctr4.update([2,2,3,1])
print(ctr4)
# Counter Methods
# 1.elements()
ctr5 = Counter([1, 9, 2, 3, 3, 3])
items = list(ctr5.elements())
print(items)
# 2.most_common()
ctr6 = Counter([1, 2, 2, 3, 3, 3,3,4,4,4,4,4,4])
common = ctr6.most_common(2)
print(common)
# 3.subtract()
ctr7 = Counter([1, 2, 2, 3, 3, 3])
ctr7.subtract([2,3])
print(ctr7)
# Arithmetic Operations on Counters
ctr8 = Counter([1,2,3,2])
ctr9 = Counter([1,2,3,5])
print(ctr8 + ctr9)
print(ctr8 - ctr9)
print(ctr9 & ctr9)
print(ctr8 | ctr9)