You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
934 B
Python

"""Solution to 2020/07 Part 1"""
import pprint
from collections import defaultdict
# key: bag, value: list of bags in wich it can be contained
tree = defaultdict(list)
def words(sentence, start, end):
"""
Strips consecutive words from a sentance
Words are whitespace separated.
Words are 1-indexed.
"""
return ' '.join(sentence.split(' ')[start-1:end])
with open('input', 'r') as f:
for line in f.readlines():
source, targets = line.strip().split(' contain ')
source = words(source, 1, 2)
for target in targets.split(', '):
target = words(target, 2, 3)
tree[target].append(source)
# pprint.pprint(tree)
processed = set()
queue = set(['shiny gold'])
count = 0
while len(queue):
cur = queue.pop()
for target in tree[cur]:
if target not in processed:
queue.add(target)
processed.add(target)
print(len(processed))