Day 2 - Advent of Code 2023

Working solutions for the day 2 puzzles.

Part One

""" day_02_01.py """

# usage: python3 day_02_01.py < input

import sys


def parse(text):
    """ extract game information """
    x, y = text.strip().split(': ')
    y = [z.split(', ') for z in y.split('; ')]
    y = [dict([tuple(reversed(w.split(' '))) for w in z]) for z in y]

    return int(x.split(' ')[-1]), y


bag = {'red': 12, 'green': 13, 'blue': 14}
answer = 0

for detail in sys.stdin:

    game, plays = parse(detail)
    for play in plays:
        for colour, number in play.items():
            if not (okay := bag[colour] >= int(number)):
                break
        if not okay:
            break
    else:
        answer += game

print(answer)

Part Two

""" day_02_02.py """

# usage: python3 day_02_02.py < input

import math
import sys


def parse(text):
    """ extract game information """
    _, y = text.strip().split(': ')
    y = [z.split(', ') for z in y.split('; ')]
    y = [dict([tuple(reversed(w.split(' '))) for w in z]) for z in y]

    return y


answer = 0

for detail in sys.stdin:

    plays = parse(detail)
    needed = {}
    for play in plays:
        for colour, number in play.items():
            needed[colour] = max(needed.get(colour, 0), int(number))
    answer += math.prod(needed.values())

print(answer)