day2.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import re
  2. from collections import defaultdict
  3. with open("aoc2023/day2/example.txt") as example:
  4. example = example.readlines()
  5. example_games = {}
  6. for line in example:
  7. cubes = defaultdict(list)
  8. spline = line.split(": ")
  9. id = spline[0].split(" ")[-1]
  10. for tri in spline[1].split("; "):
  11. for color in tri.split(", "):
  12. color = color.split()
  13. cubes[color[1]].append(int(color[0]))
  14. example_games[int(id)] = cubes
  15. # examples[id] =
  16. with open("aoc2023/day2/input.txt") as input:
  17. input = input.readlines()
  18. input_games = {}
  19. for line in input:
  20. cubes = defaultdict(list)
  21. spline = line.split(": ")
  22. id = spline[0].split(" ")[-1]
  23. for tri in spline[1].split("; "):
  24. for color in tri.split(", "):
  25. color = color.split()
  26. cubes[color[1]].append(int(color[0]))
  27. input_games[int(id)] = cubes
  28. with open("aoc2023/day1/example2.txt") as example2:
  29. example2 = example2.readlines()
  30. mapping = {
  31. "red": 12,
  32. "green": 13,
  33. "blue": 14,
  34. }
  35. not_valid = set()
  36. for id, game in example_games.items():
  37. for color in game:
  38. for num in game[color]:
  39. if num > mapping[color]:
  40. not_valid.add(id)
  41. print(sum((set(example_games) - not_valid)))
  42. not_valid = set()
  43. for id, game in input_games.items():
  44. for color in game:
  45. for num in game[color]:
  46. if num > mapping[color]:
  47. not_valid.add(id)
  48. # print(not_valid)
  49. print(sum((set(input_games) - not_valid)))
  50. sum = 0
  51. for id, game in example_games.items():
  52. power = 1
  53. for color in game:
  54. power *= max(game[color])
  55. sum += power
  56. print(sum)
  57. sum = 0
  58. for id, game in input_games.items():
  59. power = 1
  60. for color in game:
  61. power *= max(game[color])
  62. sum += power
  63. print(sum)