solution.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/python3
  2. import sys
  3. def possible(game):
  4. return not (game['red'] > 12 or game['green'] > 13 or game['blue'] > 14)
  5. # very unclean, but works
  6. def part1():
  7. print('part 1')
  8. game_id = 1
  9. summed = 0
  10. for line in sys.stdin:
  11. left, right = line.strip().split(':')
  12. game_id = int(left.lstrip('Game '))
  13. configs = [[subset.strip() for subset in subsets.split(',')] for subsets in right.split(';')]
  14. games = []
  15. for config in configs:
  16. game = {'red': 0, 'green': 0, 'blue': 0}
  17. reds = greens = blues = 0
  18. for cubes in config:
  19. if cubes.endswith(' red'):
  20. game['red'] += int(cubes.rstrip(' red'))
  21. elif cubes.endswith(' green'):
  22. game['green'] += int(cubes.rstrip(' green'))
  23. elif cubes.endswith(' blue'):
  24. game['blue'] += int(cubes.rstrip(' blue'))
  25. games.append(game)
  26. is_possible = True
  27. for game in games:
  28. if not possible(game):
  29. is_possible = False
  30. break
  31. if is_possible:
  32. summed += game_id
  33. print(summed)
  34. def part2():
  35. print('part 2')
  36. game_id = 1
  37. powers = 0
  38. for line in sys.stdin:
  39. left, right = line.strip().split(':')
  40. game_id = int(left.lstrip('Game '))
  41. configs = [[subset.strip() for subset in subsets.split(',')] for subsets in right.split(';')]
  42. games = []
  43. mins = {'red': 0, 'green': 0, 'blue': 0}
  44. for config in configs:
  45. game = {'red': 0, 'green': 0, 'blue': 0}
  46. reds = greens = blues = 0
  47. for cubes in config:
  48. if cubes.endswith(' red'):
  49. game['red'] += int(cubes.rstrip(' red'))
  50. elif cubes.endswith(' green'):
  51. game['green'] += int(cubes.rstrip(' green'))
  52. elif cubes.endswith(' blue'):
  53. game['blue'] += int(cubes.rstrip(' blue'))
  54. mins['red'] = max(mins['red'], game['red'])
  55. mins['blue'] = max(mins['blue'], game['blue'])
  56. mins['green'] = max(mins['green'], game['green'])
  57. games.append(game)
  58. powers += mins['red'] * mins['green'] * mins['blue']
  59. print(powers)
  60. if sys.argv[1] in '1':
  61. part1()
  62. else:
  63. part2()