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.

at main 49 lines 902 B view raw
1import fileinput 2from collections import defaultdict 3from utils import parse_line 4 5GOAL = 'shiny gold' 6 7graph = defaultdict(set) 8 9for i, line in enumerate(fileinput.input()): 10 line = line.strip() 11 color, rest = parse_line(r'(\w+ \w+) bags contain (.+)+', line) 12 rest = rest.replace('.', '').split(',') 13 14 for r in rest: 15 if r != 'no other bags': 16 parts = r.split() 17 new_color = ' '.join(parts[1:3]) 18 graph[color].add((new_color, int(parts[0]))) 19 20 21def dfs_1(node): 22 if node == GOAL: 23 return True 24 25 return any(dfs_1(n) for n, _ in graph[node]) 26 27 28def dfs_2(node, count=1): 29 tot = 1 30 31 for nxt, amt in graph[node]: 32 tot += dfs_2(nxt, amt) 33 34 return count * tot 35 36part_1 = 0 37 38keys = graph.keys() 39 40for bag in keys: 41 print bag 42 if dfs_1(bag): 43 part_1 += 1 44 print "good" 45 46print part_1 - 1 47 48 49print dfs_2(GOAL) - 1