Skip to content

Instantly share code, notes, and snippets.

@seblin

seblin/day7.py Secret

Last active December 7, 2020 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seblin/52b63d94550f429e004ec3245902ed0b to your computer and use it in GitHub Desktop.
Save seblin/52b63d94550f429e004ec3245902ed0b to your computer and use it in GitHub Desktop.
# https://adventofcode.com/2020/day/7
from pathlib import Path
import re
INPUT_FILE = Path(__file__).parent / "input.txt"
NEEDLE = "shiny gold"
def parse_rules(stream):
rules = {}
for line in stream:
bag = re.match("[a-z]+ [a-z]+", line).group()
contents = re.findall("(\d+) ([a-z]+ [a-z]+)", line)
rules[bag] = {name: int(amount) for amount, name in contents}
return rules
def get_super_bags(rules, needle):
queue = set([needle])
result = set()
while queue:
needle = queue.pop()
for bag, contents in rules.items():
if needle in contents:
queue.add(bag)
result.add(bag)
return result
def count_total_bags(rules, needle):
sub_amounts = (
amount * count_total_bags(rules, bag)
for bag, amount in rules[needle].items()
)
return 1 + sum(sub_amounts)
def main():
with INPUT_FILE.open() as stream:
rules = parse_rules(stream)
print(len(get_super_bags(rules, NEEDLE)))
print(count_total_bags(rules, NEEDLE) - 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment