/
15-2.py
53 lines (41 loc) · 1.18 KB
/
15-2.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
import sys
import pytest
from pathlib import Path
from textwrap import dedent
def get_hash(word: str) -> int:
total = 0
for c in word:
total = ((total + ord(c)) * 17) % 256
return total
def solve(text: str) -> int:
boxes = [{} for _ in range(256)]
for word in text.strip().split(","):
if "=" in word:
label, focall = word.split("=")
box_i = get_hash(label)
boxes[box_i][label] = int(focall)
else:
label = word.split("-")[0]
box_i = get_hash(label)
boxes[box_i].pop(label, None)
total = 0
for box_i, box in enumerate(boxes):
for label_i, (label, focall) in enumerate(box.items()):
total += (box_i + 1) * (label_i + 1) * focall
return total
if __name__ == "__main__":
p = Path(sys.argv[1])
print(solve(p.read_text()))
def test():
text = dedent(
"""
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7
"""
).strip()
assert solve(text) == 145
def test_input():
p = Path("15.txt")
if not p.exists():
pytest.skip(f"{p} does not exist")
text = p.read_text()
assert solve(text) == 271384