Advent of Code 2020, days 7, 8 and 9
I’m a bit late, so here are days 7 to 9. As now usual, all my solutions are available on https://git.sr.ht/~schnouki/advent-of-code.
### Day 7: Handy Haversacks
Bags inside bags inside bags… Do we have recursive bags now? 😯
Anyway. The first step is to parse those descriptions into something more usable. I’ve decided to do it without regexps, and storing data in simple dicts:
def parse_rule_line(line: str) -> Tuple[str, Dict[str, int]]:
"""Parse 1 rule line.
>>> parse_rule_line("light red bags contain 1 bright white bag, 2 muted yellow bags.")
('light red', {'bright white': 1, 'muted yellow': 2})
>>> parse_rule_line("faded blue bags contain no other bags.")
('faded blue', {})
"""
words = line.split()
container_color = " ".join(words[:2])
if words[4] == "no":
return (container_color, {})
bags = {}
for idx in range(4, len(words), 4):
color = " ".join(words[idx + 1 : idx + 3])
bags[color] = int(words[idx])
return (container_color, bags)
data = {}
for line in raw_data.splitlines():
color, bags = parse_rule_line(line.strip())
data[color] = bags
#### Part 1: how many bags can contain a shiny gold bag?
The first obvious (to me) way to solve this was to rewrite rules android substitute colors that can contain the target color recursively. It works… but is slow and complex.