From 1c9a6171dcbf891c8f1e0c225283c43da834f1e1 Mon Sep 17 00:00:00 2001 From: Nathan van Ofwegen Date: Mon, 7 Dec 2020 22:01:35 +0100 Subject: [PATCH] Nice. --- day7/day7.py | 87 +++++++++++++++++++--------------------------------- 1 file changed, 32 insertions(+), 55 deletions(-) diff --git a/day7/day7.py b/day7/day7.py index 6b5b992..d7aef07 100644 --- a/day7/day7.py +++ b/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)