forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtop_1.py
More file actions
46 lines (33 loc) · 959 Bytes
/
top_1.py
File metadata and controls
46 lines (33 loc) · 959 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
40
41
42
43
44
45
46
"""
Top 1 (Mode)
Find the most frequently occurring value(s) in an array. When multiple
values share the highest frequency, all are returned.
Reference: https://en.wikipedia.org/wiki/Mode_(statistics)
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
from typing import Any
def top_1(array: list[Any]) -> list[Any]:
"""Find the statistical mode(s) of an array.
Args:
array: Input list of comparable elements.
Returns:
List of element(s) with the highest frequency.
Examples:
>>> top_1([1, 1, 2, 2, 3])
[1, 2]
"""
frequency = {}
for element in array:
if element in frequency:
frequency[element] += 1
else:
frequency[element] = 1
max_count = max(frequency.values())
result = []
for element, count in frequency.items():
if count == max_count:
result.append(element)
return result