Solve day 3 (Python)

This commit is contained in:
Kiril Kovachev 2024-12-06 05:13:07 +00:00
parent 614e50c8a3
commit e5a2a3a704

33
q3.py Normal file
View File

@ -0,0 +1,33 @@
import re
MUL_PATTERN = re.compile(r"mul\((\d+), *(\d+)\)")
def task1(text: str) -> int:
total = 0
for mul in MUL_PATTERN.finditer(text):
a, b = map(int, mul.groups())
total += a*b
return total
MUL_OR_DO_PATTERN = re.compile(r"do\(\)|don't\(\)|mul\((\d+), *(\d+)\)")
def task2(text: str) -> int:
total = 0
on = True
for op in MUL_OR_DO_PATTERN.finditer(text):
if op.group(0) == "do()":
on = True
if op.group(0) == "don't()":
on = False
if op.group(1) and on:
a, b = map(int, op.groups())
total += a*b
return total
def main():
with open("i3.txt") as f:
text = f.read()
print(task1(text))
print(task2(text))
if __name__ == "__main__":
main()