From e5a2a3a7040dfa3fc56ca2118400d26590afef4a Mon Sep 17 00:00:00 2001 From: Kiril Kovachev Date: Fri, 6 Dec 2024 05:13:07 +0000 Subject: [PATCH] Solve day 3 (Python) --- q3.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 q3.py diff --git a/q3.py b/q3.py new file mode 100644 index 0000000..7aedf95 --- /dev/null +++ b/q3.py @@ -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()