32 lines
946 B
Python
32 lines
946 B
Python
|
import aocd
|
||
|
|
||
|
def get_calibrations(data):
|
||
|
for line in data.split('\n'):
|
||
|
target, *operands = line.replace(':', '').split()
|
||
|
yield int(target), tuple(int(n) for n in operands)
|
||
|
|
||
|
def can_produce_target(target, operands, current=0):
|
||
|
# Base case, we're out of numbers to apply
|
||
|
if not operands:
|
||
|
return target == current
|
||
|
|
||
|
# We've gone too high
|
||
|
if current > target:
|
||
|
return False
|
||
|
|
||
|
return can_produce_target(target, operands[1:], current + operands[0]) \
|
||
|
or can_produce_target(target, operands[1:], current * operands[0])
|
||
|
|
||
|
def solve(data):
|
||
|
return sum(target*can_produce_target(target, operands) for target, operands in get_calibrations(data))
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
puz = aocd.models.Puzzle(year=2024, day=7)
|
||
|
|
||
|
# data = puz.examples[0].input_data
|
||
|
data = puz.input_data
|
||
|
|
||
|
solution = solve(data)
|
||
|
|
||
|
print(solution)
|
||
|
aocd.submit(solution, year=2024, day=7, part='a')
|