44 lines
984 B
Python
44 lines
984 B
Python
from collections import Counter
|
|
|
|
class Polymer:
|
|
def __init__(self, data, remove=None):
|
|
self.units = list(filter(lambda u: u.lower() != remove, data))
|
|
self.index = 0
|
|
|
|
def __len__(self):
|
|
return len(self.units)
|
|
|
|
def test(self, i):
|
|
try:
|
|
a, b = self.units[i], self.units[i + 1]
|
|
except IndexError:
|
|
return False
|
|
if a != b and a.lower() == b.lower():
|
|
return True
|
|
return False
|
|
|
|
def react(self):
|
|
while self.test(self.index):
|
|
del self.units[self.index:self.index + 2]
|
|
if self.index > 0:
|
|
self.index -= 1
|
|
|
|
def process(self):
|
|
while self.index < len(self) - 1:
|
|
self.react()
|
|
self.index += 1
|
|
|
|
|
|
|
|
with open('data/05.txt') as f:
|
|
data = f.read().strip()
|
|
|
|
|
|
results = []
|
|
for unit_type in set(data.lower()):
|
|
p = Polymer(data, remove=unit_type)
|
|
p.process()
|
|
results.append(len(p))
|
|
|
|
print(min(results))
|