49 lines
1.0 KiB
Python
49 lines
1.0 KiB
Python
from collections import defaultdict
|
|
|
|
|
|
rules = {}
|
|
|
|
|
|
# with open("sample.txt") as f:
|
|
with open("input.txt") as f:
|
|
sp = list(f.readline().strip())
|
|
f.readline()
|
|
for line in f.readlines():
|
|
l, r = line.strip().split(" -> ")
|
|
rules[l] = r
|
|
|
|
|
|
start_poly = defaultdict(lambda: 0)
|
|
for i in range(0, len(sp) - 1):
|
|
start_poly[sp[i] + sp[i + 1]] += 1
|
|
|
|
|
|
def mutate(poly):
|
|
new_poly = defaultdict(lambda: 0)
|
|
for pair, count in poly.items():
|
|
new_c = rules[pair]
|
|
np1 = pair[0] + new_c
|
|
np2 = new_c + pair[1]
|
|
new_poly[np1] += count
|
|
new_poly[np2] += count
|
|
return new_poly
|
|
|
|
|
|
def get_counts(d):
|
|
counts = defaultdict(lambda: 0)
|
|
for chars, count in d.items():
|
|
counts[chars[0]] += count # only count 1st letter, the second was duplicated in a later pair
|
|
|
|
# except the last char in the original sequence
|
|
counts[sp[-1]] += 1
|
|
|
|
return dict(counts)
|
|
|
|
|
|
for i in range(0, 40):
|
|
start_poly = mutate(start_poly)
|
|
|
|
counts = sorted(get_counts(start_poly).values())
|
|
|
|
print(counts[-1] - counts[0])
|