You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.2 KiB
47 lines
1.2 KiB
#!/usr/bin/env python3
|
|
|
|
import sys, re
|
|
|
|
|
|
def HASH(string):
|
|
res = 0
|
|
for a in string:
|
|
res += ord(a)
|
|
res = res * 17 % 256
|
|
return res
|
|
|
|
|
|
if __name__ == '__main__':
|
|
instr = open(sys.argv[1]).read().strip('\n').split(',')
|
|
|
|
# challenge 1
|
|
res1 = sum([HASH(a) for a in instr])
|
|
|
|
boxes = {}
|
|
for i in instr:
|
|
label, op, focus = re.findall(r'(\w+)(\-|\=)(\d*)', i)[0]
|
|
box = HASH(label)
|
|
if not box in boxes.keys(): boxes[box] = []
|
|
present = boxes[box]
|
|
if op == '=':
|
|
for i, lens in enumerate(present):
|
|
if lens[0] == label: present[i] = (label, int(focus))
|
|
if not (label, int(focus)) in present: present.append((label, int(focus)))
|
|
elif op == '-':
|
|
for i, lens in enumerate(present):
|
|
if lens[0] == label:
|
|
present.remove(lens)
|
|
break
|
|
|
|
res2 = 0
|
|
for b, lenses in boxes.items():
|
|
for i,l in enumerate(lenses):
|
|
res2 += (b+1) * (i+1) * l[1]
|
|
|
|
res1 = str(res1)
|
|
print(f"challenge 1:\n{res1}\n")
|
|
|
|
# challenge 2
|
|
res2 = str(res2)
|
|
print(f"challenge 2:\n{res2}\n")
|
|
|
|
|