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
My cleanest solution! Wrote more about it, even tested networkx in my blogpost.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Python
My cleanest solution! Wrote more about it, even tested networkx in my blogpost.