advent_of_code/2021/14/14_2_bad.py

51 lines
1.2 KiB
Python
Raw Permalink Normal View History

2022-04-05 12:35:16 +02:00
#!/usr/bin/env python
# 2021 - Advent Of Code - 14 part 2
from collections import Counter
def parse_file(file):
2022-04-05 13:27:24 +02:00
with open(file, encoding="utf-8") as f:
2022-04-05 12:35:16 +02:00
poly_string = list(f.readline().strip())
f.readline()
insertion_rules = dict([line.strip().split(' -> ') for line in f.readlines()])
return poly_string, insertion_rules
def step_poly(poly_str, ruleset):
new_p = []
2022-04-05 14:02:10 +02:00
p = None
2022-04-05 12:35:16 +02:00
l_poly = len(poly_str)
for i, p in enumerate(poly_str):
if i + 1 == l_poly:
break
binome = '' + p + poly_str[i+1]
# print(f'binome {binome}')
found = ruleset.get(binome)
#if found:
# # print(f'found: {found}')
# new_p.extend([p, found])
#else:
# new_p.append(p)
new_p.extend([p, found])
new_p.append(p)
return ''.join(new_p)
# poly, rules = parse_file('input_example.txt')
poly, rules = parse_file('input.txt')
print(f'poly: {poly}')
print(f'rules: {rules}')
for s in range(22):
#for s in range(17):
print(f'step: {s}')
poly = step_poly(poly, rules)
# print(poly)
print(Counter(poly))
c = Counter(poly).most_common()[0][1] - Counter(poly).most_common()[-1][1]
print(c)