Files
AoC-2020/day7/day7.py
2020-12-07 22:02:48 +01:00

68 lines
1.4 KiB
Python

def gettree():
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:
rule = words[5] + " " + words[6]
num = int(words[4])
tree[top_bag][rule] = num
else:
rule = words[2] + " " + words[3]
num = int(words[1])
tree[top_bag][rule] = num
return tree
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):
rule = tree[bag]
sum = 0
for child in rule:
sum += rule[child] + (rule[child] * countBags(child, tree))
return sum
def part1():
tree = gettree()
count = 0
for bag in tree:
if countShine(bag, tree) > 0:
count += 1
print("Part 1: %d" % count)
def part2():
tree = gettree()
count = countBags('shiny gold', tree)
print("Part 2: %d" % count)
if __name__ == "__main__":
part1()
part2()