import itertools import math import sys lines = sys.stdin.read().splitlines() 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 # part 1 answer_1 = len(path(next(node for node in nodes if node.endswith("A")))) - 1 print(f"answer 1 is {answer_1}") # part 2 answer_2 = math.lcm(*(len(path(node)) - 1 for node in nodes if node.endswith("A"))) print(f"answer 2 is {answer_2}")