advent-of-code-2024/day3.2.py

35 lines
766 B
Python
Raw Permalink Normal View History

2024-12-03 13:57:28 -08:00
""" day3 """
import re
import fileinput
def match_all(pending):
active = True
result = 0
while pending:
instr = re.search(r'(do|don\'t|mul)\(([0-9,]*)\)', pending)
if not instr:
break
pending = pending[instr.span()[1]:]
op=instr[1]
args=instr[2].split(',')
print(f'active={active} op={op} args={args}')
if op == 'do':
active = True
elif op == 'don\'t':
active = False
elif active and op == 'mul':
if len(args) == 2 and 1 <= len(args[0]) <= 3 and 1 <= len(args[1]) <= 3:
result += int(args[0]) * int(args[1])
return result
input = ''
for line in fileinput.input():
input += line
print(match_all(input))