import sys L = sys.stdin.read().splitlines() seed = L[0] L = L[2:] L = [ l.split() for l in L ] D = { tuple(k):v for [k,_,v] in L } print(seed, D) for step in range(10): C = ["X"] # X is their to avoid empty list when comparing to previous char for (a,b) in zip(seed, seed[1:]): if a != C[-1]: C.append(a) if (a,b) in D: C.append(D[(a,b)]) C.append(b) seed = "".join(C) print(step+1, len(seed), seed[1:]) from collections import Counter C = Counter(seed) del C["X"] print(C, C.values(), max(C.values())-min(C.values())) # store 40 iterations will be 20*2^39~=21TB ...