Files
AoC-2020/day7/day7.py
2020-12-07 21:50:49 +01:00

92 lines
2.0 KiB
Python

def countShine(bag, tree):
item = tree[bag]
if 'shiny gold' in item:
return item['shiny gold']
else:
sum = 0
for child in tree[bag]:
sum += countShine(child, tree)
return sum
def countBags(bag, tree):
item = tree[bag]
sum = 0
for child in item:
sum += item[child] + (item[child] * countBags(child, tree))
return sum
def part1():
file = open("input.txt")
tree = {}
for bag_line in file:
bags = bag_line.strip().split(",")
top_bag_line = bags[0].split(" ")
top_bag = top_bag_line[0] + " " + top_bag_line[1]
tree[top_bag] = {}
for index, bag in enumerate(bags):
words = bag.split(" ")
if words[4] == 'no':
continue
if index == 0:
mBag = words[5] + " " + words[6]
mNum = int(words[4])
tree[top_bag][mBag] = mNum
else:
mBag = words[2] + " " + words[3]
mNum = int(words[1])
tree[top_bag][mBag] = mNum
count = 0
for bag in tree:
shines = countShine(bag, tree)
if shines > 0:
count += 1
print("Part 1: %d" % count)
def part2():
file = open("input.txt")
tree = {}
for bag_line in file:
bags = bag_line.strip().split(",")
top_bag_line = bags[0].split(" ")
top_bag = top_bag_line[0] + " " + top_bag_line[1]
tree[top_bag] = {}
for index, bag in enumerate(bags):
words = bag.split(" ")
if words[4] == 'no':
continue
if index == 0:
mBag = words[5] + " " + words[6]
mNum = int(words[4])
tree[top_bag][mBag] = mNum
else:
mBag = words[2] + " " + words[3]
mNum = int(words[1])
tree[top_bag][mBag] = mNum
count = countBags('shiny gold', tree)
print("Part 2: %d" % count)
if __name__ == "__main__":
part1()
part2()