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.
47 lines
1.1 KiB
Python
47 lines
1.1 KiB
Python
"""Solution to 2020/07 Part 2"""
|
|
|
|
import pprint
|
|
from collections import defaultdict
|
|
|
|
|
|
# key: bag, value: list of tuples (count, bag which must 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)
|
|
if targets == 'no other bags.':
|
|
continue
|
|
for target in targets.split(', '):
|
|
count = int(target.split(' ')[0])
|
|
color = words(target, 2, 3)
|
|
tree[source].append((count, color))
|
|
|
|
# pprint.pprint(tree)
|
|
|
|
processed = set()
|
|
queue = [(1, 'shiny gold')]
|
|
count = 0
|
|
|
|
while len(queue):
|
|
source_count, source = queue.pop()
|
|
count += source_count
|
|
for target_count, target in tree[source]:
|
|
queue.append((source_count * target_count, target))
|
|
|
|
print(count - 1)
|
|
|
|
# Wrong: 41560
|