Advertisement
icarussiano

Day 3 python

Dec 3rd, 2023 (edited)
616
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. import re
  2.  
  3. with open("input") as file:
  4.     data = file.read().splitlines()
  5. num = []
  6. sym = []
  7. gear = []
  8. part1 = 0
  9. part2 = 0
  10.  
  11. for line in data:
  12.     num.append([(int(m.group()),m.start(), m.end() - 1) for m in re.finditer(r'(\d+)', line)])
  13.     sym.append([m.start() for m in re.finditer(r'[^\d.]', line)])
  14.     gear.append([m.start() for m in re.finditer(r'\*', line)])
  15.  
  16. for i, x in enumerate(num):
  17.     for n, s, e in x:
  18.         if ((s - 1 in sym[i]) or (e + 1 in sym[i]) or
  19.                 (i != len(num) - 1 and any(x in sym[i + 1] for x in range(s - 1, e + 2))) or
  20.                 (i != 0 and any(x in sym[i - 1] for x in range(s - 1, e + 2)))):
  21.             part1 += n
  22.  
  23. for i in range(1,len(num)-1):
  24.     for g in gear[i]:
  25.         r = range(g - 1, g + 2)
  26.         boh = {(n,s,e) for n, s, e in num[i] if s - 1 == g or e + 1 == g} | {(n,s,e) for n, s, e in num[i - 1] if s in r or e in r} | {(n,s,e) for n, s, e in num[i + 1] if s in r or e in r}
  27.         if len(boh) == 2:
  28.             prod = 1
  29.             for n,s,e in boh:
  30.                 prod *= n
  31.             part2+=prod
  32.  
  33. print(part1,part2)
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement