Skip to content

Commit

Permalink
Faster to split by literal string
Browse files Browse the repository at this point in the history
  • Loading branch information
ephemient committed Dec 3, 2024
1 parent 0f3e7f2 commit 2f2b94d
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions py/aoc2024/day3.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,26 @@
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:
"""
>>> 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:
"""
>>> 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)

0 comments on commit 2f2b94d

Please sign in to comment.