Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def day15(s, *, part2=False):
- s = s.strip()
- def my_hash(s2):
- # return 0 if not s2 else ((my_hash(s2[:-1]) + ord(s2[-1])) * 17) % 256
- h = 0
- for ch in s2:
- h = ((h + ord(ch)) * 17) % 256
- return h
- if not part2:
- return sum(my_hash(instruction) for instruction in s.split(','))
- boxes = [[] for _ in range(256)]
- for instruction in s.split(','):
- label, op, focal = hh.re_groups(r'^(.+)([-=])(.*)$', instruction)
- box_index = my_hash(label)
- if op == '-':
- boxes[box_index] = [(l, f) for l, f in boxes[box_index] if l != label]
- else:
- indices = [i for i, (l, f) in enumerate(boxes[box_index]) if l == label]
- if indices:
- boxes[box_index][indices[0]] = label, focal
- else:
- boxes[box_index].append((label, focal))
- return sum((b + 1) * (i + 1) * int(f) for b in range(256) for i, (l, f) in enumerate(boxes[b]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement