#!/usr/bin/env python3 import functools lines = (x.strip() for x in open("input.txt")) instructions = tuple(int(char == "R") for char in next(lines)) next(lines) nodes = {line[:3]: (line[7:10], line[12:15]) for line in lines} def get_loop(node: str): cnt = 0 while True: for char in instructions: node = nodes[node][char] cnt += 1 if node[2] == "Z": return cnt def lcm(a, b): mul = abs(a * b) while b: a, b = b, a % b return mul // a curr_nodes = tuple(key for key in nodes.keys() if key[2] == "A") loops = map(get_loop, curr_nodes) print(functools.reduce(lcm, loops, 1))