Created
December 7, 2020 18:49
-
-
Save pjhoberman/45e7db474047d6821a3c805977ecc332 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from collections import defaultdict | |
from copy import deepcopy | |
with open('/Users/pjhoberman/Library/Application Support/JetBrains/PyCharm2020.2/scratches/scratch_21.txt') as file: | |
data = file.read() | |
rules = data.splitlines() | |
parse_re = r"(\w+ \w+) bags contain (.*)" | |
contents_re = r"(\d+) (\w+ \w+)" | |
parsed_rules = defaultdict(list) | |
def parse_rule(rule): | |
m = re.fullmatch(parse_re, rule) | |
bag_color, contents = m.groups() | |
contents = contents.split(", ") | |
for content in contents: | |
if content == 'no other bags.': | |
continue | |
q, inner_bag_color = re.match(contents_re, content).groups() | |
parsed_rules[bag_color].append({'bag_color': inner_bag_color, 'q': q}) | |
for rule in rules: | |
parse_rule(rule) | |
bag_map = defaultdict(set) | |
def build_bag_map(color, parents): | |
if parsed_rules.get(color, None): | |
for bag in parsed_rules.get(color, []): | |
for c in parents: | |
bag_map[c].add(bag.get('bag_color')) | |
_parents = deepcopy(parents) | |
_parents.add(bag.get('bag_color')) | |
build_bag_map(bag.get('bag_color'), parents=_parents) | |
for bag_color in parsed_rules: | |
build_bag_map(bag_color, parents={bag_color}) | |
len(list(filter(lambda bag: "shiny gold" in bag, bag_map.values()))) | |
def traverse_bags(color, multiplier): | |
global count | |
for bag in parsed_rules[color]: | |
count += int(bag.get('q')) * multiplier | |
traverse_bags(bag.get('bag_color'), multiplier * int(bag.get('q'))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment