#!/usr/bin/python3 from pprint import pprint import re rules = {} with open("input") as fh: for ln in fh: m = re.fullmatch(r"(.*) bags contain (.*)\.\n", ln) container = m.group(1) contents = {} for c in m.group(2).split(", "): if m := re.match(r"(\d+) (.*) bag", c): contents[m.group(2)] = int(m.group(1)) assert container not in rules # Assume only one rule for each container rules[container] = contents def nr_contained_bags(color): contents = rules[color] sum = 0 for color2, count in contents.items(): sum += count * (1 + nr_contained_bags(color2)) return sum print(nr_contained_bags("shiny gold"))