-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathcounting.py
74 lines (52 loc) · 1.67 KB
/
counting.py
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# Take 1
def get_number_with_highest_count(counts): # <1>
max_count = 0
for number, count in counts.items():
if count > max_count:
max_count = count
number_with_highest_count = number
return number_with_highest_count
def most_frequent(numbers):
counts = {}
for number in numbers: # <2>
if number in counts:
counts[number] += 1
else:
counts[number] = 1
return get_number_with_highest_count(counts)
# Using defaultdict
from collections import defaultdict # <1>
def get_number_with_highest_count(counts):
max_count = 0
for number, count in counts.items():
if count > max_count:
max_count = count
number_with_highest_count = number
return number_with_highest_count
def most_frequent(numbers):
counts = defaultdict(int) # <2>
for number in numbers:
counts[number] += 1 # <3>
return get_number_with_highest_count(counts)
# Using Counter
from collections import Counter # <1>
def get_number_with_highest_count(counts):
max_count = 0
for number, count in counts.items():
if count > max_count:
max_count = count
number_with_highest_count = number
return number_with_highest_count
def most_frequent(numbers):
counts = Counter(numbers) # <2>
return get_number_with_highest_count(counts)
# Using lambda functions
from collections import Counter
def get_number_with_highest_count(counts):
return max( # <1>
counts,
key=lambda number: counts[number]
)
def most_frequent(numbers):
counts = Counter(numbers)
return get_number_with_highest_count(counts)