47 lines
1,015 B
Python
47 lines
1,015 B
Python
import os
|
|
import sys
|
|
from collections import defaultdict
|
|
|
|
def hash(s):
|
|
v = 0
|
|
for c in s:
|
|
if c == ",":
|
|
continue
|
|
v += ord(c)
|
|
v *= 17
|
|
v %= 256
|
|
return v
|
|
|
|
with open(sys.argv[1]) as f:
|
|
s = f.read().strip()
|
|
|
|
boxes = defaultdict(list)
|
|
|
|
part1 = 0
|
|
for s_ in s.split(","):
|
|
part1 += hash(s_)
|
|
|
|
if s_[-1] == "-":
|
|
label = s_[:-1]
|
|
h = hash(label)
|
|
for i in range(len(boxes[h])):
|
|
if boxes[h][i][0] == label:
|
|
del boxes[h][i]
|
|
break
|
|
elif s_[-2] == "=":
|
|
label = s_[:-2]
|
|
focal = int(s_[-1])
|
|
h = hash(label)
|
|
for i in range(len(boxes[h])):
|
|
if boxes[h][i][0] == label:
|
|
boxes[h][i] = (label, focal)
|
|
break
|
|
else:
|
|
boxes[h].append((label, focal))
|
|
|
|
part2 = 0
|
|
for (box_i, box) in boxes.items():
|
|
for (slot, (_, focal)) in enumerate(box):
|
|
part2 += (box_i + 1) * (slot + 1) * focal
|
|
|
|
print(part1, part2)
|