From 56fb20e704dac203f54cfdb39c96eaeefa8e22ed Mon Sep 17 00:00:00 2001 From: Lucidiot Date: Wed, 5 Dec 2018 08:10:36 +0100 Subject: [PATCH] 2018 day 5 part 2 --- 2018/5/alchemy.py | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/2018/5/alchemy.py b/2018/5/alchemy.py index b1300a6..bfdc6ab 100755 --- a/2018/5/alchemy.py +++ b/2018/5/alchemy.py @@ -1,19 +1,35 @@ #!/usr/bin/env python3 +from multiprocessing import Pool from string import ascii_lowercase, ascii_uppercase import fileinput import re +REACT_SET = set(map(''.join, zip(ascii_lowercase, ascii_uppercase))) +REACT_SET = REACT_SET.union({r[::-1] for r in REACT_SET}) +REACT_REGEX = re.compile(r'({})'.format('|'.join(REACT_SET))) -def main(): - removals = set(map(''.join, zip(ascii_lowercase, ascii_uppercase))) - removals = removals.union({r[::-1] for r in removals}) - remove_regex = re.compile('({})'.format('|'.join(removals))) - line = next(fileinput.input()).strip() + +def react(polymer): count = 1 while count > 0: - line, count = remove_regex.subn('', line) - return len(line) + polymer, count = REACT_REGEX.subn('', polymer) + return len(polymer) + + +def react_without(polymer, letter): + print('Reacting without letter {}'.format(letter)) + return react(polymer.replace(letter, '').replace(letter.upper(), '')) + + +def main(): + line = next(fileinput.input()).strip() + + print('Reacting full line') + print(react(line)) + + with Pool(4) as p: + print(min(p.starmap(react_without, ((line, letter) for letter in ascii_lowercase)))) if __name__ == '__main__': - print(main()) + main()