69 lines
1.4 KiB
Python
69 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:
|
|
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
|
|
|
|
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):
|
|
item = tree[bag]
|
|
sum = 0
|
|
for child in item:
|
|
sum += item[child] + (item[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()
|