2020/Day 7/two.py

46 lines
1.2 KiB
Python
Raw Normal View History

2022-07-01 15:56:12 +02:00
#!/bin/python
# faded blue bags contain 0 other bags.
# dotted black bags contain 0 other bags.
# vibrant plum bags contain 11 other bags: 5 faded blue bags and 6 dotted black bags.
# dark olive bags contain 7 other bags: 3 faded blue bags and 4 dotted black bags.
# shiny gold bags contain 3 other bags: 1 dark olive bag and 2 vibrant plume bags
# 7 + 2*11
def check(bag, rules):
result = 0
for needed_bag, amount in rules[bag].items():
if rules[needed_bag] == {}:
result += amount
else:
result += amount + amount * check(needed_bag, rules)
return result
# $color bags contain {$number $color bags,}*x
# color: {colors}
with open("input", 'r') as input:
rules = {}
for line in input:
line = line.strip()
parts = line.split(" bags contain ")
key = parts[0]
value = {}
parts = parts[1].strip(".").split(", ")
for part in parts:
if part == "no other bags":
break;
bag_parts = part.split(" ", 1)
value[bag_parts[1].replace("bags", "").replace("bag", "").strip()] = int(bag_parts[0])
rules[key] = value
print(check("shiny gold", rules))