solution.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/env python3
  2. import sys
  3. import re
  4. def inc(dictionary, key):
  5. try:
  6. dictionary[key] += 1
  7. except KeyError:
  8. dictionary[key] = 1
  9. polymer = {}
  10. template = input()
  11. for p in template:
  12. inc(polymer, p)
  13. rules = {}
  14. for line in sys.stdin:
  15. if line == '\n': continue
  16. source, target = [ group for group in re.match(r'([a-zA-Z]{2}) -> ([a-zA-Z])', line).groups() ]
  17. rules[source] = target
  18. for i in range(int(sys.argv[1]) if len(sys.argv) > 1 else 16):
  19. template_new = []
  20. prev = template[0]
  21. template_new.append(prev)
  22. for c in template[1:]:
  23. insertion = rules[prev + c]
  24. inc(polymer, insertion)
  25. template_new.append(insertion)
  26. template_new.append(c)
  27. prev = c
  28. print(f'at step {i}: {template} -> {"".join(template_new)} {polymer}')
  29. template = ''.join(template_new)
  30. l = min([polymer[p] for p in polymer.keys()])
  31. m = max([polymer[p] for p in polymer.keys()])
  32. print(f'the most common element ({m}) minus the least common element ({l}) yields a difference of {m - l}')