DEV Community

loading...

Discussion on: Advent of Code 2020 Solution Megathread - Day 7: Handy Haversacks

Collapse
cnille profile image
Christopher Nilsson

Python

import re
from collections import defaultdict

bags = defaultdict(dict)
for l in lines:
    bag = re.match(r'(.*) bags contain', l).groups()[0]
    for count, b in re.findall(r'(\d+) (\w+ \w+) bag', l):
        bags[bag][b] = int(count)

def part1():
    answer = set()
    def search(color):
        for b in bags:
            if color in bags[b]:
                answer.add(b)
                search(b)
    search('shiny gold')
    return len(answer)

def part2():
    def search(bag):
        count = 1
        for s in bags[bag]:
            multiplier = bags[bag][s]
            count += multiplier * search(s)
        return count
    return search('shiny gold' ) - 1  # Rm one for shiny gold itself
Enter fullscreen mode Exit fullscreen mode

My cleanest solution! Wrote more about it, even tested networkx in my blogpost.