44 lines
711 B
Python
44 lines
711 B
Python
|
#!/usr/bin/env python3
|
||
|
|
||
|
import re
|
||
|
|
||
|
with open("day03") as f:
|
||
|
i = f.read()
|
||
|
|
||
|
# 1
|
||
|
|
||
|
pat = re.compile(r"mul\(([0-9]+),([0-9]+)\)")
|
||
|
|
||
|
muls = re.findall(pat, i)
|
||
|
|
||
|
res = 0
|
||
|
for mul in muls:
|
||
|
res += int(mul[0]) * int(mul[1])
|
||
|
|
||
|
|
||
|
# 2
|
||
|
|
||
|
pat = re.compile(r"(mul\(([0-9]+),([0-9]+)\)|do\(\)|don't\(\))")
|
||
|
|
||
|
muls = re.findall(pat, i)
|
||
|
|
||
|
res = 0
|
||
|
|
||
|
def consume_disabled(muls):
|
||
|
for mul in muls:
|
||
|
if mul[0] == "do()":
|
||
|
consume_enabled(muls)
|
||
|
|
||
|
def consume_enabled(muls):
|
||
|
global res
|
||
|
for mul in muls:
|
||
|
if mul[0] == "don't()":
|
||
|
consume_disabled(muls)
|
||
|
if mul[0].startswith("mul"):
|
||
|
res += int(mul[1]) * int(mul[2])
|
||
|
|
||
|
gen = (m for m in muls)
|
||
|
consume_enabled(gen)
|
||
|
|
||
|
print(res)
|