Day 7
This commit is contained in:
91
day7/day7.py
Normal file
91
day7/day7.py
Normal file
@@ -0,0 +1,91 @@
|
||||
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()
|
||||
Reference in New Issue
Block a user