day4.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import os
  2. from itertools import accumulate
  3. from collections import defaultdict
  4. with open(os.path.join(os.path.dirname(__file__), "example.txt")) as example:
  5. example_data = example.read().splitlines()
  6. with open(os.path.join(os.path.dirname(__file__), "input.txt")) as example:
  7. input_data = example.read().splitlines()
  8. import time
  9. def bench(part):
  10. def wrapper(*args, **kwargs):
  11. start = time.perf_counter()
  12. value = part(*args, **kwargs)
  13. print(f"\tevaluation time: {time.perf_counter() - start} s")
  14. return value
  15. return wrapper
  16. @bench
  17. def solve1(data):
  18. total_points = 0
  19. for line in data:
  20. line = line.split(": ")[-1]
  21. have, win = line.split("|")
  22. have = [int(n) for n in have.split()]
  23. win = [int(n) for n in win.split()]
  24. try:
  25. *_, points = accumulate(
  26. (1 for _ in have if _ in win), func=lambda x, _: x * 2
  27. )
  28. except Exception:
  29. points = 0
  30. total_points += points
  31. print(total_points)
  32. solve1(example_data)
  33. solve1(input_data)
  34. @bench
  35. def solve2(data):
  36. cards = defaultdict(lambda: 1)
  37. for ind, line in enumerate(data):
  38. cards[ind + 1]
  39. line = line.split(": ")[-1]
  40. have, win = line.split("|")
  41. have = [int(n) for n in have.split()]
  42. win = [int(n) for n in win.split()]
  43. mat = sum((1 for _ in have if _ in win))
  44. for card in range(ind + 2, ind + 2 + mat):
  45. cards[card] += cards[ind + 1]
  46. print(sum(cards.values()))
  47. solve2(example_data)
  48. solve2(input_data)