import re import math f = open('input.txt', 'r') data = f.read().strip() instructions = data.split('\n')[0] table = data.split('\n\n')[1].split('\n') tuplemap = {} sources_list_par2 = [] for tuple in table: source, left, right = re.findall(r"[A-Z]{3}", tuple) tuplemap[source] = (left, right) if source[2] == 'A': sources_list_par2.append(source) current_symbol = 'AAA' i = 0 mod = len(instructions) steps = 0 while current_symbol != 'ZZZ': steps += 1 current_move = instructions[i] i += 1 i %= mod if current_move == 'L': current_symbol = tuplemap[current_symbol][0] else: current_symbol = tuplemap[current_symbol][1] sources_length_part2 = [] for s in sources_list_par2: current_symbol = s i = 0 steps_p2 = 0 while current_symbol[2] != 'Z': steps_p2 += 1 current_move = instructions[i] i += 1 i %= mod if current_move == 'L': current_symbol = tuplemap[current_symbol][0] else: current_symbol = tuplemap[current_symbol][1] sources_length_part2.append(steps_p2) steps_part2 = math.lcm(*sources_length_part2) print("Part 1:", steps) print("Part 2:", steps_part2)