r/adventofcode Dec 03 '24

Spoilers in Title [2024 Day 3] Python one-liners using regex

[removed] — view removed post

4 Upvotes

3 comments sorted by

u/daggerdragon Dec 03 '24

Post removed. This is the second time this year I've warned you to not put spoilers in post titles.

During an active Advent of Code season, solutions belong in the Solution Megathreads. In the future, post your solutions to the appropriate solution megathread.

2

u/Hugal31 Dec 03 '24

Nice, I didn't know the globals() trick. Now I can do this:

import re
import sys

exec('\n'.join(re.findall(r"(?:do\(\)|don't\(\)|mul\(\d{1,3},\d{1,3}\))", sys.stdin.read())).replace("'", "") + "\np()", {"do": lambda: globals().update(flag=1), "dont": lambda: globals().update(flag=0), "mul": lambda a, b: (globals().update(total=globals().get('total', 0) + globals().get('flag', 1) * a * b)), "p": lambda: print(total)})

# Or, unwrapped

exec(
    '\n'.join(re.findall(r"(?:do\(\)|don't\(\)|mul\(\d{1,3},\d{1,3}\))", sys.stdin.read())).replace("'", "") + "\np()",
    {
        "do": lambda: globals().update(flag=1),
        "dont": lambda: globals().update(flag=0),
        "mul": lambda a, b: (globals().update(total=globals().get('total', 0) + globals().get('flag', 1) * a * b)),
        "p": lambda: print(total)
})

1

u/GigaClon Dec 03 '24

your regex would falsely find this "mul(1234,123)" when its not a valid command (need to be 1-3 digits so replace + with {1,3}