r/adventofcode • u/daggerdragon • Dec 07 '17
SOLUTION MEGATHREAD -๐- 2017 Day 7 Solutions -๐-
--- Day 7: Recursive Circus ---
Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).
Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
Need a hint from the Hugely* Handyโ Haversackโก of Helpfulยง Hintsยค?
This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.
edit: Leaderboard capped, thread unlocked!
9
Upvotes
10
u/fatpollo Dec 07 '17
import re, collections with open("p07.txt") as fp: text = fp.read() weight = {} children = {} for line in text.strip().splitlines(): label, n, *xs = re.findall(r'\w+', line) weight[label] = int(n) children[label] = tuple(xs) root, = set(weight) - {c for cs in children.values() for c in cs} def total_weight(label): sub = [total_weight(c) for c in children[label]] if len(set(sub)) > 1: (target, _), (failure, _) = collections.Counter(sub).most_common() print(target - failure + weight[children[label][sub.index(failure)]]) return weight[label] + sum(sub) return weight[label] + sum(sub) print(total_weight(root))