with open("i19.txt", "r") as f: data = f.read() eqs = [] molecule = "" for line in data.splitlines(): if "=>" in line: lhs, rhs = line.split(" => ") eqs.append((lhs, rhs)) elif line: molecule = line.strip() molecules = set() for lhs, rhs in eqs: for i in range(len(molecule)): f, t = molecule[:i], molecule[i:] if t.startswith(lhs): n = f + t.replace(lhs, rhs, 1) molecules.add(n) print(len(molecules)) # It seems like the problem input is specifically designed so that reversing # the molecule back to 'e' works by simply replacing RHS with LHS continuously. # Intuitively, it seems like this should not work in many cases or at least not # result in the shortest sequence. Probably I am just salty that it took me so # long to find this trivial solution. x = molecule count = 0 while len(x) > 1: old_len = len(x) for lhs, rhs in eqs: if rhs in x: x = x.replace(rhs, lhs, 1) count += 1 break else: break assert x == 'e' print(count)