From bc41afab0f7a592fc81117135c8572f53742a4b4 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 9 Dec 2023 09:47:24 +0000 Subject: [PATCH] 2023: d09: ex2: add solution --- 2023/d09/ex2/ex2.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100755 2023/d09/ex2/ex2.py diff --git a/2023/d09/ex2/ex2.py b/2023/d09/ex2/ex2.py new file mode 100755 index 0000000..122bc46 --- /dev/null +++ b/2023/d09/ex2/ex2.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + +import itertools +import sys + + +def solve(input: list[str]) -> int: + def parse_line(line: str) -> list[int]: + return [int(n) for n in line.split()] + + def parse(input: list[str]) -> list[list[int]]: + return [parse_line(line) for line in input] + + def extrapolate(sequence: list[int]) -> int: + diffs = [n - p for p, n in itertools.pairwise(sequence)] + if all(n == 0 for n in diffs): + return sequence[-1] + return sequence[-1] + extrapolate(diffs) + + sequences = parse(input) + + return sum(extrapolate(seq[::-1]) for seq in sequences) + + +def main() -> None: + input = sys.stdin.read().splitlines() + print(solve(input)) + + +if __name__ == "__main__": + main()