-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7.py
More file actions
42 lines (36 loc) · 1.29 KB
/
7.py
File metadata and controls
42 lines (36 loc) · 1.29 KB
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
with open("7.txt") as f:
rules=f.read().splitlines()
rules=[r[:-1] for r in rules]
ruleDic={" ".join(rule.split(" ")[:2]): rule.split("contain ")[1].split(", ") for rule in rules}
for k in ruleDic.keys():
if 'no other bags' in ruleDic[k]:
continue
ruleDic[k] =[e[2:-5] if e[0]!="1" else e[2:-4] for e in ruleDic[k] ]
changed=True
validBags=set()
validBags.add("shiny gold")
while changed:
newValids=set()
for k,v in ruleDic.items():
for color in v :
if color in validBags and not k in validBags:
newValids.add(k)
changed=newValids
validBags=set.union(validBags,newValids)
validBags.remove("shiny gold")
print("\nAnswer part one: ",len(validBags))
####Part 2####
ruleDic={" ".join(rule.split(" ")[:2]): rule.split("contain ")[1].split(", ") for rule in rules}
for k in ruleDic.keys():
if 'no other bags' in ruleDic[k]:
continue
ruleDic[k] =[(e[2:-5],int(e[0])) if e[0]!="1" else (e[2:-4],int(e[0])) for e in ruleDic[k] ]
def bagsCount(color):
if "no other bags" in ruleDic[color]:
return 1
totalBags = 0
for tup in ruleDic[color]:
totalBags+=(tup[1]*bagsCount(tup[0]))
print("for ",color," returning: ",totalBags)
return totalBags+1
print("Answer part two: ", bagsCount("shiny gold")-1)