forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmisra_gries.py
More file actions
70 lines (55 loc) · 1.79 KB
/
misra_gries.py
File metadata and controls
70 lines (55 loc) · 1.79 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
Misra-Gries Frequency Estimation
Given a list of items and a value k, returns every item that appears at least
n/k times, where n is the length of the list. Defaults to k=2 (majority
problem).
Reference: https://en.wikipedia.org/wiki/Misra%E2%80%93Gries_summary
Complexity:
Time: O(n * k)
Space: O(k)
"""
from __future__ import annotations
def misras_gries(array: list[int], k: int = 2) -> dict[str, int] | None:
"""Find all elements appearing at least n/k times.
Args:
array: A list of integers.
k: The frequency threshold divisor (default 2).
Returns:
A dict mapping element (as string) to its frequency, or None
if no element meets the threshold.
Examples:
>>> misras_gries([1, 4, 4, 4, 5, 4, 4])
{'4': 5}
>>> misras_gries([0, 0, 0, 1, 1, 1, 1])
{'1': 4}
>>> misras_gries([0, 0, 0, 0, 1, 1, 1, 2, 2], 3)
{'0': 4, '1': 3}
"""
keys: dict[str, int] = {}
for item in array:
val = str(item)
if val in keys:
keys[val] += 1
elif len(keys) < k - 1:
keys[val] = 1
else:
for key in list(keys):
keys[key] -= 1
if keys[key] == 0:
del keys[key]
suspects = keys.keys()
frequencies: dict[str, int] = {}
for suspect in suspects:
freq = _count_frequency(array, int(suspect))
if freq >= len(array) / k:
frequencies[suspect] = freq
return frequencies if frequencies else None
def _count_frequency(array: list[int], element: int) -> int:
"""Count occurrences of element in array.
Args:
array: The list to search.
element: The value to count.
Returns:
The number of occurrences.
"""
return array.count(element)