From 0f3e7f21da0a91ac0176010940bb45b854413435 Mon Sep 17 00:00:00 2001 From: Daniel Lin Date: Tue, 3 Dec 2024 07:45:47 -0500 Subject: [PATCH 1/2] Reuse part 1 in part 2 --- py/aoc2024/day3.py | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/py/aoc2024/day3.py b/py/aoc2024/day3.py index 960bd4fd..b1b40e89 100644 --- a/py/aoc2024/day3.py +++ b/py/aoc2024/day3.py @@ -12,7 +12,7 @@ """ _pattern1 = re.compile(r"mul\((\d+),(\d+)\)") -_pattern2 = re.compile(r"(do\(\))|(don't\(\))|mul\((\d+),(\d+)\)") +_pattern2 = re.compile(r"(?:\A|do\(\))(.*?)(?:\Z|don't\(\))", re.S) def part1(data: str) -> int: @@ -28,15 +28,7 @@ def part2(data: str) -> int: >>> part2(SAMPLE_INPUT_2) 48 """ - enabled, total = True, 0 - for m in _pattern2.finditer(data): - if m.group(1): - enabled = True - elif m.group(2): - enabled = False - elif enabled: - total += int(m.group(3)) * int(m.group(4)) - return total + return sum(part1(m.group(1)) for m in _pattern2.finditer(data)) parts = (part1, part2) From 2f2b94daf4f8464bacaa7a40f0414b90dc42ae13 Mon Sep 17 00:00:00 2001 From: Daniel Lin Date: Tue, 3 Dec 2024 07:51:31 -0500 Subject: [PATCH 2/2] Faster to split by literal string --- py/aoc2024/day3.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/py/aoc2024/day3.py b/py/aoc2024/day3.py index b1b40e89..85560f2f 100644 --- a/py/aoc2024/day3.py +++ b/py/aoc2024/day3.py @@ -11,8 +11,7 @@ xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) """ -_pattern1 = re.compile(r"mul\((\d+),(\d+)\)") -_pattern2 = re.compile(r"(?:\A|do\(\))(.*?)(?:\Z|don't\(\))", re.S) +_pattern = re.compile(r"mul\((\d+),(\d+)\)") def part1(data: str) -> int: @@ -20,7 +19,7 @@ def part1(data: str) -> int: >>> part1(SAMPLE_INPUT_1) 161 """ - return sum(int(m.group(1)) * int(m.group(2)) for m in _pattern1.finditer(data)) + return sum(int(m.group(1)) * int(m.group(2)) for m in _pattern.finditer(data)) def part2(data: str) -> int: @@ -28,7 +27,10 @@ def part2(data: str) -> int: >>> part2(SAMPLE_INPUT_2) 48 """ - return sum(part1(m.group(1)) for m in _pattern2.finditer(data)) + return sum( + part1(subdata[: subdata.index("don't()")] if "don't()" in subdata else subdata) + for subdata in data.split("do()") + ) parts = (part1, part2)