From b918737ed1f55c6556eeb4e439d0fe66613d6d45 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 7 Dec 2024 10:43:00 +0000 Subject: [PATCH] 2024: d07: ex1: add solution --- 2024/d07/ex1/ex1.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100755 2024/d07/ex1/ex1.py diff --git a/2024/d07/ex1/ex1.py b/2024/d07/ex1/ex1.py new file mode 100755 index 0000000..ee7bd9a --- /dev/null +++ b/2024/d07/ex1/ex1.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python + +import operator +import sys + + +def solve(input: str) -> int: + def parse(input: list[str]) -> list[tuple[int, list[int]]]: + return [ + (int(value), [int(n) for n in numbers.split()]) + for value, numbers in map(lambda l: l.split(": "), input) + ] + + def solvable(target: int, numbers: list[int]) -> bool: + def helper(current_value: int, current_index: int) -> bool: + next_index = current_index + 1 + if len(numbers) == next_index: + return target == current_value + if current_value > target: + return False + for op in (operator.add, operator.mul): + if helper(op(current_value, numbers[next_index]), next_index): + return True + return False + + return helper(numbers[0], 0) + + equations = parse(input.splitlines()) + return sum(value for value, numbers in equations if solvable(value, numbers)) + + +def main() -> None: + input = sys.stdin.read() + print(solve(input)) + + +if __name__ == "__main__": + main()