advent-of-code/2023/python/day02.py

66 lines
1.4 KiB
Python
Raw Permalink Normal View History

2023-12-03 01:56:00 +00:00
import shared
from collections import defaultdict
2023-12-08 18:42:42 +00:00
2023-12-03 01:56:00 +00:00
def split_games(row):
game, draws = row.split(":")
game = int(game.split(" ")[-1])
colors = defaultdict(list)
for draw in draws.split(";"):
for cube in draw.split(","):
cube = cube.split()
count, color = cube
colors[color].append(int(count))
2023-12-08 18:42:42 +00:00
return game, colors
2023-12-03 01:56:00 +00:00
MAXES = {
"red": 12,
2023-12-08 18:42:42 +00:00
"green": 13,
2023-12-03 01:56:00 +00:00
"blue": 14,
}
2023-12-08 18:42:42 +00:00
2023-12-03 01:56:00 +00:00
# @shared.profile
def part1(rows):
applicable = []
for row in rows:
ok = True
game, colors = split_games(row)
for color, _max in MAXES.items():
bag_max = max(colors[color])
if bag_max > _max:
ok = False
break
if ok:
applicable.append(game)
print(sum(applicable))
# @shared.profile
def part2(rows):
2023-12-03 02:18:25 +00:00
total = 0
for row in rows:
_, colors = split_games(row)
2023-12-08 18:42:42 +00:00
power = 1
2023-12-03 02:18:25 +00:00
for vals in colors.values():
power *= max(vals)
total += power
print(total)
2023-12-03 01:56:00 +00:00
def main():
rows = [row for row in shared.load_rows(2)]
with shared.elapsed_timer() as elapsed:
part1(rows)
print("🕒", elapsed())
2023-12-03 04:12:04 +00:00
rows = [row for row in shared.load_rows(2, True)]
2023-12-03 01:56:00 +00:00
with shared.elapsed_timer() as elapsed:
part2(rows)
print("🕒", elapsed())
if __name__ == "__main__":
main()