advent-of-code/2023/day9.py
Mikaël Capelle 7c6c9e5995 2023 day 9.
2023-12-09 08:08:46 +01:00

30 lines
729 B
Python

import sys
lines = sys.stdin.read().splitlines()
data = [[int(c) for c in line.split()] for line in lines]
right_values: list[int] = []
left_values: list[int] = []
for values in data:
diffs = [values]
while any(d != 0 for d in diffs[-1]):
diffs.append([rhs - lhs for lhs, rhs in zip(diffs[-1][:-1], diffs[-1][1:])])
rhs: list[int] = [0]
lhs: list[int] = [0]
for cx in range(len(diffs) - 1):
rhs.append(diffs[-cx - 2][-1] + rhs[cx])
lhs.append(diffs[-cx - 2][0] - lhs[cx])
right_values.append(rhs[-1])
left_values.append(lhs[-1])
# part 1
answer_1 = sum(right_values)
print(f"answer 1 is {answer_1}")
# part 2
answer_2 = sum(left_values)
print(f"answer 2 is {answer_2}")