Day 7 - Advent of Code 2024
7 December 2024
Working solutions for the day 7 puzzles.
Part One
""" day_07_01.py """
# usage: python3 day_07_01.py < input
import re
import sys
from itertools import product
def valid(answer, args):
""" operators * and + are left associative """
for ops in product('+*', repeat=len(args) - 1):
expr = args[0]
for i, j in enumerate(ops):
expr = str(eval(expr + j + args[i + 1]))
if answer == expr:
return True
return False
with sys.stdin as infile:
equations = [re.findall(r'\d+', line) for line in infile]
print(sum(int(equation[0]) for equation in equations
if valid(equation[0], equation[1:])))
Part Two
""" day_07_02.py """
# usage: python3 day_07_02.py < input
import re
import sys
from itertools import product
def valid(answer, args):
""" operators *, + and || are left associative """
for ops in product('+*|', repeat=len(args) - 1):
expr = args[0]
for i, j in enumerate(ops):
if j == '|':
expr += args[i + 1]
else:
expr = str(eval(expr + j + args[i + 1]))
if answer == expr:
return True
return False
with sys.stdin as infile:
equations = [re.findall(r'\d+', line) for line in infile]
print(sum(int(equation[0]) for equation in equations
if valid(equation[0], equation[1:])))