My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Update 2017/day07.py

+29 -14
+29 -14
2017/day07.py
··· 1 - import sys 2 1 import re 3 2 import fileinput 4 3 ··· 39 38 print 'Name of bottom program:', root.name 40 39 41 40 41 + BAD_WEIGHTS = {} 42 + 43 + 42 44 def program_weight(node): 43 45 if not node.aboves: 44 46 return node.weight 45 47 46 48 weights = [program_weight(a) for a in node.aboves] 47 49 48 - # Since we're performing DFS, we are guaranteed to encounter the problem 49 - # disc here first; therefore, we compute the correct answer and exit. 50 + # Keep track of discs whose children have different weights 50 51 if len(set(weights)) != 1: 51 - for i, w in enumerate(weights): 52 - if weights.count(w) == 1: 53 - diff = w 54 - wrong_disc = node.aboves[i].name 55 - else: 56 - same = w 57 - 58 - proper_weight = DISCS[wrong_disc].weight + (same - diff) 59 - print "Proper weight of `{}`: {}".format(wrong_disc, proper_weight) 60 - sys.exit() 52 + BAD_WEIGHTS[node.name] = weights 61 53 62 54 return sum(weights) + node.weight 63 55 64 56 65 - # Initialize the recursion, which will also find the solution. 57 + # Seed `BAD_WEIGHTS` 66 58 program_weight(root) 59 + 60 + # Traverse from root until the offending disc is found 61 + bad_disc = root 62 + while True: 63 + for a in bad_disc.aboves: 64 + if a.name in BAD_WEIGHTS: 65 + bad_disc = a 66 + break 67 + else: 68 + break 69 + 70 + # Determine the correct weight of the child disc 71 + weights = BAD_WEIGHTS[bad_disc.name] 72 + 73 + for i, w in enumerate(weights): 74 + if weights.count(w) == 1: 75 + diff = w 76 + wrong_disc = bad_disc.aboves[i].name 77 + else: 78 + same = w 79 + 80 + proper_weight = DISCS[wrong_disc].weight + (same - diff) 81 + print "Proper weight of `{}`: {}".format(wrong_disc, proper_weight)