summaryrefslogtreecommitdiffstats
path: root/2020/day7/inside_shiny.py
diff options
context:
space:
mode:
authorYigit Sever2021-12-12 01:24:32 +0300
committerYigit Sever2021-12-12 01:24:32 +0300
commit4bb6f8d06c0e384f3394012b1d48da58ed28cc5e (patch)
treed6478c85c0488a1059567ccd2882cb10039c2546 /2020/day7/inside_shiny.py
parentae3853b6e8ab02023ccd74baac6dc177b1ee879a (diff)
downloadaoc-4bb6f8d06c0e384f3394012b1d48da58ed28cc5e.tar.gz
aoc-4bb6f8d06c0e384f3394012b1d48da58ed28cc5e.tar.bz2
aoc-4bb6f8d06c0e384f3394012b1d48da58ed28cc5e.zip
2020, tracking
Diffstat (limited to '2020/day7/inside_shiny.py')
-rw-r--r--2020/day7/inside_shiny.py45
1 files changed, 45 insertions, 0 deletions
diff --git a/2020/day7/inside_shiny.py b/2020/day7/inside_shiny.py
new file mode 100644
index 0000000..00df40b
--- /dev/null
+++ b/2020/day7/inside_shiny.py
@@ -0,0 +1,45 @@
1import networkx as nx
2import re
3
4
5def fits_in(root):
6 """recursively count the number of bags that fit in other bags
7
8 :root: the node to count bags from
9 :returns: total
10
11 """
12 total = 1
13 for neighbour in bagtree[root]:
14 total += int(bagtree[root][neighbour]["weight"]) * fits_in(neighbour)
15 return total
16
17
18bagtree = nx.DiGraph()
19bagremover = re.compile(r" bags?\.?$")
20countandbag = re.compile(r"(\d+) (\w+ \w+)")
21
22with open("input", "r") as baglines:
23 for line in baglines:
24 (miniroot, child_str) = list(map(str.strip, line.split("contain")))
25
26 miniroot = miniroot.replace(" bags", "")
27
28 children = list(
29 map(
30 lambda a: re.sub(bagremover, "", a),
31 list(map(str.strip, child_str.split(","))),
32 )
33 )
34
35 if "no other" in children:
36 continue
37
38 for kid in children:
39 matches = re.match(countandbag, kid)
40 bagtree.add_edge(miniroot, matches.groups()[1], weight=matches.groups()[0])
41
42lengths = dict(nx.all_pairs_shortest_path(bagtree))
43
44# we don't count the shiny gold itself
45print(fits_in("shiny gold") - 1)