We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent d03579d commit 1355f54Copy full SHA for 1355f54
1 file changed
rounds/1_histogram/solution.py
@@ -5,17 +5,29 @@
5
own faster implementation.
6
"""
7
8
+from array import array
9
+
10
11
def compute_histogram(path: str) -> dict[bytes, int]:
12
with open(path, "rb") as f:
13
data = f.read()
14
- counts = {}
15
+ n = len(data)
16
+ if n < 2:
17
+ return {}
18
19
+ # 65,536 possible 2-byte combinations
20
+ counts = array("I", [0]) * 65536
21
22
+ prev = data[0]
23
- for a, b in zip(data, data[1:]):
- k = (a << 8) | b
- counts[k] = counts.get(k, 0) + 1
24
+ for i in range(1, n):
25
+ curr = data[i]
26
+ counts[(prev << 8) | curr] += 1
27
+ prev = curr
28
29
return {
- k.to_bytes(2, "big"): v
- for k, v in counts.items()
30
+ i.to_bytes(2, "big"): count
31
+ for i, count in enumerate(counts)
32
+ if count
33
}
0 commit comments