Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- with open("input") as file:
- data = file.read().splitlines()
- num = []
- sym = []
- gear = []
- part1 = 0
- part2 = 0
- for line in data:
- num.append([(int(m.group()),m.start(), m.end() - 1) for m in re.finditer(r'(\d+)', line)])
- sym.append([m.start() for m in re.finditer(r'[^\d.]', line)])
- gear.append([m.start() for m in re.finditer(r'\*', line)])
- for i, x in enumerate(num):
- for n, s, e in x:
- if ((s - 1 in sym[i]) or (e + 1 in sym[i]) or
- (i != len(num) - 1 and any(x in sym[i + 1] for x in range(s - 1, e + 2))) or
- (i != 0 and any(x in sym[i - 1] for x in range(s - 1, e + 2)))):
- part1 += n
- for i in range(1,len(num)-1):
- for g in gear[i]:
- r = range(g - 1, g + 2)
- 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}
- if len(boh) == 2:
- prod = 1
- for n,s,e in boh:
- prod *= n
- part2+=prod
- print(part1,part2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement