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 = 20 state = '..' * gens + initial_state + '..' * gens print(state) for _ in range(gens): next = ['.', '.'] for i in range(2, len(state) - 2): seq = state[i-2:i+3] next.append(rules.get(seq) or '.') next.append('.') next.append('.') state = ''.join(next) print(state.strip('.')) res = 0 for i, pot_val in enumerate(state): pot_id = i - gens * 2 if pot_val == '#': res += pot_id print(res)