blob: 3c0d0e37c315e359264f8f7679ef27ffb2e53b7d (
plain) (
blame)
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
|
#!/usr/bin/env python3
bdict: dict[str, list[str]] = {}
# Recursively check if a bag can hold a shiny gold bag
def holds_bag(innerbags: list[str]) -> bool:
if "no other" in innerbags:
return False
elif "shiny gold" in innerbags:
return True
return any(holds_bag(bdict[subbag]) for subbag in innerbags)
def main() -> None:
global bdict
with open("input", "r", encoding="utf-8") as f:
lines = f.readlines()
for baginfo in lines:
data = baginfo.split(" bags contain")
# { bag_name: [contained_bag_1, containted_bag_2, ...] }
bdict[data[0]] = [" ".join(b.split(" ")[-3:][:2]) for b in data[1].split(",")]
print(sum(holds_bag(bdict[bag]) for bag in bdict))
if __name__ == "__main__":
main()
|