aboutsummaryrefslogtreecommitdiff
path: root/2020/07/puzzle-2.py
diff options
context:
space:
mode:
authorThomas Voss <thomasvoss@live.com> 2021-10-29 23:02:39 +0200
committerThomas Voss <thomasvoss@live.com> 2021-10-29 23:02:39 +0200
commite7c9108b95e39d7ea5a29ae06d619c4727f11027 (patch)
tree237261eef3afd0720be77dbcbb9599fa66a24b67 /2020/07/puzzle-2.py
Initial commit
Diffstat (limited to '2020/07/puzzle-2.py')
-rwxr-xr-x2020/07/puzzle-2.py35
1 files changed, 35 insertions, 0 deletions
diff --git a/2020/07/puzzle-2.py b/2020/07/puzzle-2.py
new file mode 100755
index 0000000..c87ea13
--- /dev/null
+++ b/2020/07/puzzle-2.py
@@ -0,0 +1,35 @@
+#!/usr/bin/env python3
+
+
+bdict: dict[str, list[str]] = {}
+
+# Recursively find the number of sub-bags in a bag
+def total_bags(innerbags: list[dict[int, str]]) -> int:
+ if innerbags[0]["name"] == "no other":
+ return 0
+
+ return sum([bag["count"] + bag["count"] * total_bags(bdict[bag["name"]]) for bag in innerbags])
+
+
+def main() -> None:
+ with open("input", "r") as f:
+ lines = f.readlines()
+
+ for baginfo in lines:
+ data = baginfo.split(" bags contain")
+
+ # { bag_name: [{ count: n, name: bag_name_ }, ...] }
+ bdict[data[0]] = []
+ for b in data[1].split(","):
+ bdict[data[0]].append(
+ {
+ "count": int(b.replace("no", "0").split(" ")[1]),
+ "name": " ".join(b.split(" ")[-3:][:2]),
+ }
+ )
+
+ print(total_bags(bdict["shiny gold"]))
+
+
+if __name__ == "__main__":
+ main()