Skip to content

Instantly share code, notes, and snippets.

@rodrigogiraoserrao
Created December 3, 2024 21:31
Show Gist options
  • Save rodrigogiraoserrao/5e46a146c0e68c71b7d391a05e8f95d2 to your computer and use it in GitHub Desktop.
Save rodrigogiraoserrao/5e46a146c0e68c71b7d391a05e8f95d2 to your computer and use it in GitHub Desktop.
# === 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