-
Notifications
You must be signed in to change notification settings - Fork 0
/
d7-code.py
86 lines (70 loc) · 2.46 KB
/
d7-code.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# import pyperclip
# import sys
# f = open("day7-input.txt", "r")
# curr_l = 0
# total_l = 594
# final = 0
# while True:
# for line in f:
# if curr_l != total_l:
# line = line.strip()
# pass
# curr_l += 1
# else:
# print(final)
# pyperclip.copy(final)
# sys.exit(0)
def parse(filename):
"""Parse the input file to form two digraphs: one showing
which bags are able to be contained in which and the other
showing which bags contain what numbers of which other bags.
"""
parents = dict()
children = dict()
with open(filename, "r") as f:
lines = f.readlines()
# Figure out which colors we have
for line in lines:
color = " ".join(line.split()[:2])
parents[color] = []
children[color] = []
# Fill in the digraphs
for line in lines:
words = line.split()
if "no other" in line:
continue
parent_color = " ".join(words[:2])
child_words = iter(words[4:])
while True:
count = int(next(child_words))
child_adj = next(child_words)
child_color = next(child_words)
child_name = f"{child_adj} {child_color}"
parents[child_name].append(parent_color)
children[parent_color].append((child_name, count))
if next(child_words)[-1] == ".":
break
return parents, children
def holders(color, parents_graph):
"""Build a set of all unique bags which can contain the
requested bag color.
"""
result = set(parents_graph[color])
for c in parents_graph[color]:
result |= holders(c, parents_graph)
return result
def count_contents(color, children_graph):
"""Add up the bags inside a given bag plus all of the bags within
each of each child bags.
"""
return sum(count + count * count_contents(child_color, children_graph)
for child_color, count in children_graph[color])
def part1(parents_graph):
gold_holders = len(holders("shiny gold", parents_graph))
print(f"{gold_holders} different colors can contain 'shiny gold.'")
def part2(children_graph):
print(f"{count_contents('shiny gold', children_graph)} bags are in a 'shiny gold.'")
if __name__ == "__main__":
parents, children = parse("day7-input.txt")
part1(parents)
part2(children)