1
0
advent-of-code-2k23/day2/day2.py

46 lines
1.3 KiB
Python
Raw Permalink Normal View History

2023-12-02 20:47:59 +00:00
from math import prod
def part1(lines):
result = set()
for index, line in enumerate(lines):
game_id = index + 1
2023-12-03 10:32:47 +00:00
_, line = line.split(": ")
2023-12-02 20:47:59 +00:00
result.add(int(game_id))
2023-12-03 10:32:47 +00:00
hands = line.rstrip().split("; ")
2023-12-02 20:47:59 +00:00
for hand in hands:
colors = {"red": 0, "green": 0, "blue": 0}
2023-12-03 10:32:47 +00:00
cubes = hand.split(", ")
2023-12-02 20:47:59 +00:00
for cube in cubes:
2023-12-03 10:32:47 +00:00
n, color = cube.split()
2023-12-02 20:47:59 +00:00
colors[color] = int(n)
if colors["red"] > 12 or colors["green"] > 13 or colors["blue"] > 14:
2023-12-03 10:32:47 +00:00
# impossible configuration, remove this game_id from the result (if present)
result.discard(int(game_id))
2023-12-02 20:47:59 +00:00
print(f"Part 1: {sum(result)}")
def part2(lines):
result = []
for line in lines:
colors = {"red": 0, "green": 0, "blue": 0}
2023-12-03 10:32:47 +00:00
_, line = line.split(": ")
hands = line.rstrip().split("; ")
for hand in hands:
cubes = hand.split(", ")
2023-12-02 20:47:59 +00:00
for cube in cubes:
2023-12-03 10:32:47 +00:00
n, color = cube.split()
2023-12-02 20:47:59 +00:00
colors[color] = max(colors[color], int(n))
result.append(prod(colors.values()))
print(f"Part 2: {sum(result)}")
if __name__ == "__main__":
import sys
infile = sys.argv[1]
with open(infile) as f:
lines = f.readlines()
part1(lines)
part2(lines)