28 lines
828 B
Python
28 lines
828 B
Python
#!/usr/bin/env python3
|
|
import re
|
|
from collections import Counter, defaultdict
|
|
|
|
lines = (x.strip() for x in open("input.txt"))
|
|
first = next(lines)
|
|
next(lines)
|
|
|
|
combinations = Counter(first[a:a+2] for a in range(len(first)-1))
|
|
replacements = defaultdict(list)
|
|
|
|
for line in lines:
|
|
(a, b), insert = re.match(r"([A-Z]{2}) -> ([A-Z])", line).groups()
|
|
replacements[a+insert].append(a+b)
|
|
replacements[insert+b].append(a+b)
|
|
|
|
for _ in range(10):
|
|
combinations = {
|
|
k: sum_val for k, v in replacements.items() if (sum_val := sum(combinations.get(x, 0) for x in v)) > 0
|
|
}
|
|
|
|
letters = Counter(first[0] + first[-1])
|
|
for key, cnt in combinations.items():
|
|
letters[key[0]] = letters.get(key[0], 0) + cnt
|
|
letters[key[1]] = letters.get(key[1], 0) + cnt
|
|
|
|
print((max(letters.values()) - min(letters.values())) // 2)
|