2023-12-04 18:32:41 +00:00
|
|
|
import sys
|
2023-12-15 05:23:39 +00:00
|
|
|
from functools import reduce
|
|
|
|
|
|
|
|
steps = sys.stdin.read().strip().split(",")
|
|
|
|
|
|
|
|
|
|
|
|
def _hash(s: str) -> int:
|
|
|
|
return reduce(lambda v, u: ((v + ord(u)) * 17) % 256, s, 0)
|
2023-12-04 18:32:41 +00:00
|
|
|
|
|
|
|
|
|
|
|
# part 1
|
2023-12-15 05:23:39 +00:00
|
|
|
answer_1 = sum(map(_hash, steps))
|
2023-12-04 18:32:41 +00:00
|
|
|
print(f"answer 1 is {answer_1}")
|
|
|
|
|
|
|
|
# part 2
|
2023-12-15 05:23:39 +00:00
|
|
|
boxes: list[dict[str, int]] = [{} for _ in range(256)]
|
|
|
|
|
|
|
|
for step in steps:
|
|
|
|
if (i := step.find("=")) >= 0:
|
|
|
|
label, length = step[:i], int(step[i + 1 :])
|
|
|
|
boxes[_hash(label)][label] = length
|
|
|
|
else:
|
|
|
|
label = step[:-1]
|
|
|
|
boxes[_hash(label)].pop(label, None)
|
|
|
|
|
|
|
|
answer_2 = sum(
|
|
|
|
i_box * i_lens * length
|
|
|
|
for i_box, box in enumerate(boxes, start=1)
|
|
|
|
for i_lens, length in enumerate(box.values(), start=1)
|
|
|
|
)
|
2023-12-04 18:32:41 +00:00
|
|
|
print(f"answer 2 is {answer_2}")
|