import aocd import math 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]) \ or can_produce_target(target, operands[1:], current * 10**math.floor(math.log(operands[0], 10) + 1) + 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='b')