main.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from doctest import Example
  2. import os, sys
  3. from tabnanny import check
  4. from numpy import poly
  5. task_dir = os.path.dirname(__file__)
  6. sys.path.append(f"{task_dir}/..")
  7. from get_tasks import get_input, check_example, generate_readme
  8. from collections import Counter, defaultdict
  9. def parse(input: list[str]) -> tuple[str, dict]:
  10. template = input[0]
  11. instructions = {}
  12. for line in input[2:]:
  13. key, value = line.split(" -> ")
  14. instructions[(key[0], key[1])] = value
  15. return template, instructions
  16. def polymerize(steps: int, template: str, instructions: dict) -> int:
  17. counter = Counter(template)
  18. combinations: defaultdict[tuple, int] = defaultdict(int)
  19. for i in range(len(template) - 1):
  20. combinations[(template[i], template[i + 1])] += 1
  21. for _ in range(steps):
  22. temp_combinations = combinations.copy()
  23. for comb in temp_combinations:
  24. counter[instructions[comb]] += temp_combinations[comb]
  25. combinations[comb] -= temp_combinations[comb]
  26. combinations[(comb[0], instructions[comb])] += temp_combinations[comb]
  27. combinations[(instructions[comb], comb[1])] += temp_combinations[comb]
  28. return max(counter.values()) - min(counter.values())
  29. def part1(input: list[str]):
  30. print("The answer of part1 is:", polymerize(10, *parse(input)))
  31. def part2(input: list[str]):
  32. print("The answer if part2 is:", polymerize(40, *parse(input)))
  33. if __name__ == "__main__":
  34. input, example = get_input(task_dir, 14)
  35. check_example(example, part1)
  36. check_example(example, part2)
  37. part1(input)
  38. part2(input)
  39. generate_readme(task_dir, 14)