Advertisement
Guest User

Untitled

a guest
Dec 15th, 2023
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | Source Code | 0 0
  1. from collections import OrderedDict
  2.  
  3.  
  4. path = "day_15.txt"
  5. # path = "test.txt"
  6.  
  7. with open(path, 'r') as file:
  8.     seq = file.readline()[:-1].split(',')
  9.     # print(seq)
  10.  
  11. def my_hash(s: str):
  12.     current = 0
  13.     for c in s:
  14.         current += ord(c)
  15.         current *= 17
  16.         current = current%256
  17.    
  18.     return current
  19.  
  20. boxes = [OrderedDict() for _ in range(256)]
  21. for s in seq:
  22.     label = ''
  23.     i = 0
  24.     while s[i].isalpha():
  25.         label += s[i]
  26.         i += 1
  27.    
  28.     symbol = s[i]
  29.     box = my_hash(label)
  30.  
  31.     if symbol == '-' and label in boxes[box]:
  32.         boxes[box].pop(label)
  33.     elif symbol == '=':
  34.         number = int(s[-1])
  35.         boxes[box][label] = number
  36.    
  37.    
  38. answer = [(i, b) for i,b in enumerate(boxes) if len(b.keys()) > 0]
  39. sum = 0
  40. for i,b in answer:
  41.     for j, lens in enumerate(b.values()):
  42.         sum += (i+1) * (j+1) * lens
  43. # answer = sum([my_hash(s) for s in seq])
  44. print(sum)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement