Created
December 3, 2024 21:31
-
-
Save rodrigogiraoserrao/5e46a146c0e68c71b7d391a05e8f95d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # === Parsing === | |
| import pathlib | |
| contents = pathlib.Path("input.txt").read_text() | |
| """ | |
| with open("input.txt", "r") as f: | |
| contents = f.read() | |
| """ | |
| print(contents) | |
| # === Part 1 === | |
| import re | |
| MUL = r"mul\((\d{1,3}),(\d{1,3})\)" | |
| acc = 0 | |
| for match in re.finditer(MUL, contents): | |
| num1, num2 = match.groups() | |
| acc += int(num1) * int(num2) | |
| print(acc) | |
| # === Part 2 === | |
| import re | |
| MATCHES = r"""(?x) | |
| mul\((\d{1,3}),(\d{1,3})\) # Finds mul() operations. | |
| |do\(\) # Finds do() “enablers”. | |
| |don't\(\) # Finds don't() “disablers”. | |
| """ | |
| acc = 0 | |
| enabled = True | |
| for match in re.finditer(MATCHES, contents): | |
| if match.group(0) == "do()": | |
| enabled = True | |
| elif match.group(0) == "don't()": | |
| enabled = False | |
| elif enabled: # Implicitly, it's a “mul” match. | |
| num1, num2 = match.groups() | |
| acc += int(num1) * int(num2) | |
| print(acc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment