Nice.
This commit is contained in:
87
day7/day7.py
87
day7/day7.py
@@ -1,3 +1,32 @@
|
||||
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:
|
||||
@@ -12,7 +41,6 @@ def countShine(bag, tree):
|
||||
|
||||
def countBags(bag, tree):
|
||||
item = tree[bag]
|
||||
|
||||
sum = 0
|
||||
for child in item:
|
||||
sum += item[child] + (item[child] * countBags(child, tree))
|
||||
@@ -21,68 +49,17 @@ def countBags(bag, tree):
|
||||
|
||||
|
||||
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
|
||||
|
||||
tree = gettree()
|
||||
count = 0
|
||||
for bag in tree:
|
||||
shines = countShine(bag, tree)
|
||||
if shines > 0:
|
||||
if countShine(bag, tree) > 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
|
||||
|
||||
tree = gettree()
|
||||
count = countBags('shiny gold', tree)
|
||||
|
||||
print("Part 2: %d" % count)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user