advent-of-code-2024/day7.2.py

54 lines
1.3 KiB
Python

""" day 7 part 2 """
import fileinput
import typing
def has_solution(goal, operands):
# print(f'goal={goal} operands={operands}')
if len(operands) == 0:
return ''
if len(operands) == 1:
# print(f'{goal} == {operands[0]}?')
return goal if goal == operands[0] else ''
# check add
here = operands[-1]
subgoal = operands[:-1]
if goal > here:
if prev := has_solution(goal - here, subgoal):
# print(f'{goal - here} + {here}?')
return f'{prev} + {here}'
if here == 0 or (goal / here == goal // here):
if prev := has_solution(goal // here, subgoal):
# print(f'{goal / here} * {here}?')
return f'{prev} * {here}'
suffix = str(here)
if str(goal).endswith(suffix) and str(goal) != suffix:
if prev := has_solution(int(str(goal).removesuffix(suffix)), subgoal):
return f'{prev} || {here}'
return ''
count = 0
for line in fileinput.input():
goal, _, expr = line.strip().partition(':')
# print(f'{goal} - {expr}')
goal = int(goal)
operands = [int(term) for term in expr.strip().split()]
solution = has_solution(goal, operands)
if solution:
print(f'{goal} = {solution}')
count += goal
print(count)