advent-of-code/2023/day9.py

30 lines
729 B
Python
Raw Normal View History

2023-12-04 18:32:41 +00:00
import sys
lines = sys.stdin.read().splitlines()
2023-12-09 07:08:46 +00:00
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])
2023-12-04 18:32:41 +00:00
# part 1
2023-12-09 07:08:46 +00:00
answer_1 = sum(right_values)
2023-12-04 18:32:41 +00:00
print(f"answer 1 is {answer_1}")
# part 2
2023-12-09 07:08:46 +00:00
answer_2 = sum(left_values)
2023-12-04 18:32:41 +00:00
print(f"answer 2 is {answer_2}")