advent-of-code/2023/day8.py

30 lines
680 B
Python
Raw Normal View History

2023-12-08 06:28:50 +00:00
import itertools
import math
2023-12-04 18:32:41 +00:00
import sys
lines = sys.stdin.read().splitlines()
2023-12-08 06:28:50 +00:00
sequence = lines[0]
nodes = {
p[0]: {d: n for d, n in zip("LR", p[1].strip("()").split(", "))}
for line in lines[2:]
if (p := line.split(" = "))
}
def path(start: str):
path = [start]
it_seq = iter(itertools.cycle(sequence))
while not path[-1].endswith("Z"):
path.append(nodes[path[-1]][next(it_seq)])
return path
2023-12-04 18:32:41 +00:00
# part 1
2023-12-08 06:28:50 +00:00
answer_1 = len(path(next(node for node in nodes if node.endswith("A")))) - 1
2023-12-04 18:32:41 +00:00
print(f"answer 1 is {answer_1}")
# part 2
2023-12-08 06:28:50 +00:00
answer_2 = math.lcm(*(len(path(node)) - 1 for node in nodes if node.endswith("A")))
2023-12-04 18:32:41 +00:00
print(f"answer 2 is {answer_2}")