Is it possible to rewrite the function below to use just a single regular expression to…
- User
Is it possible to rewrite the function below to use just a single regular expression to extract the correct integers to be multiplied, also handling the "do()/don't()" enable/disable in the regex patter itself? I want to remove the loop and match statement, and instead just run sum(map(lambda m: int(m[0]) * int(m[1]), matches)) after matching to get the final result.
I am guessing this might be possible with lookahead/lookbehind, but not sure. Something like "capture mul ints if preceded by do() + any random characters not including don't()", might have to append a "do()" at the beginning to get it started.
pythonimport re def solve() -> int: memory = r"xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))" matches = re.findall(r"mul\((\d{1,3}),(\d{1,3})\)|(do\(\)|don't\(\))", memory) mul_enabled = True # At the beginning of the program, mul instructions are enabled result = 0 for m in matches: match m: case (x, y, "") if mul_enabled: result += int(x) * int(y) case (*_, "do()"): mul_enabled = True case (*_, "don't()"): mul_enabled = False return resultFurther information which may be useful (we are interested in part 2): "Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though," says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look.
The shopkeeper turns to you. "Any chance you can see why our computers are having issues again?"
The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up!
It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4.
However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing.
For example, consider the following section of corrupted memory:
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.