It's ramping up. I'm learning new things.
Part 1
with open("input.txt", "r") as f:
input = f.readlines()
directions = input[0]
input.remove(directions)
input.remove("\n")
nodes = []
for line in input:
node, edges = line.split(" = (")
left, right = edges.removesuffix(")\n").split(", ")
nodes.append(dict(key=node, L=left, R=right))
found = False
key = "AAA"
steps = 0
direction_index = 0
while not found:
node = next(node for node in nodes if node["key"] == key)
key = node[directions[direction_index % (len(directions) - 1)]]
steps += 1
direction_index += 1
if key == "ZZZ":
found = True
print(steps)syntax highlighting by codehost
Part 2
import math
with open("input.txt", "r") as f:
input = f.readlines()
directions = input[0]
input.remove(directions)
input.remove("\n")
nodes = []
for line in input:
node, edges = line.split(" = (")
left, right = edges.removesuffix(")\n").split(", ")
nodes.append(dict(key=node, L=left, R=right))
start_nodes = []
for node in nodes:
if node["key"].endswith("A"):
start_nodes.append(node)
all_steps = []
for start_node in start_nodes:
found = False
steps = 0
direction_index = 0
key = start_node["key"]
while not found:
node = next(node for node in nodes if node["key"] == key)
key = node[directions[direction_index % (len(directions) - 1)]]
steps += 1
direction_index += 1
if key.endswith("Z"):
found = True
all_steps.append(steps)
print(math.lcm(*all_steps))syntax highlighting by codehost