-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmode.py
More file actions
39 lines (25 loc) · 731 Bytes
/
mode.py
File metadata and controls
39 lines (25 loc) · 731 Bytes
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
"""Find the most frequent num(s) in nums.
Return the set of nums that are the mode::
>>> find_mode([1]) == {1}
True
>>> find_mode([1, 2, 2, 2]) == {2}
True
If there is a tie, return all::
>>> find_mode([1, 1, 2, 2]) == {1, 2}
True
"""
def find_mode(nums):
"""Find the most frequent num(s) in nums."""
counts = {}
mode = set()
for num in nums:
counts[num] = counts.setdefault(num, 0) + 1
max_count = max(counts.values())
for num, count in counts.items():
if count == max_count:
mode.add(num)
return mode
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. HOORAY!\n"