import os import sys from collections import defaultdict def hash(s: str) -> int: v = 0 for c in s: if c == ",": continue v += ord(c) v *= 17 v %= 256 return v def main() -> None: with open(sys.argv[1]) as f: s = f.read().strip() boxes: defaultdict[int, list[tuple[str, int]]] = 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) if __name__ == "__main__": main()