from pprint import pprint with open('input.txt', 'r') as f: raw = [x.strip() for x in f.readlines()] initial_state = raw[0].split(' ')[-1] rules = dict() for rule in raw[2:]: x, y = rule.split(' => ') rules[x] = y print(initial_state) pprint(rules) gens = 50000000000 start_idx = 0 state = initial_state print(state) for it in range(gens): if it % 10000 == 0: print('calc at', it, 'state len:', len(state), 'idx', start_idx) print(state) next = [] state = '....' + state + '....' for i in range(2, len(state) - 2): seq = state[i-2:i+3] next.append(rules.get(seq) or '.') start_idx -= 2 state = ''.join(next) start_idx += len(state) - len(state.lstrip('.')) state = state.strip('.') # print(' ' * (start_idx + 20) + state, start_idx) res = 0 for i, pot_val in enumerate(state): pot_id = i + start_idx if pot_val == '#': res += pot_id print(res)