1
+ import os
2
+
3
+ fileName = "7.txt"
4
+ with open (fileName ) as file :
5
+ rules = {}
6
+ total = 0
7
+ text = file .readlines ()
8
+ for rule in text :
9
+ total = total + 1
10
+ myColor = rule [0 :rule .find (" bag" )]
11
+ i = rule .find ("contain" ) + 7
12
+ others = rule [i :- 2 ]
13
+ others = others .replace ("bags" ,"" )
14
+ others = others .replace ("bag" ,"" )
15
+ others = others .split ("," )
16
+ for i in range (len (others )):
17
+ others [i ] = others [i ][3 :- 1 ]
18
+ rules [myColor ] = others
19
+ #print(myColor,others)
20
+ #print(total, len(rules)) #proves rules are for unique colors
21
+ containsGold = {}
22
+ containsGold ["shiny gold" ] = True
23
+ #for rule in rules:
24
+ # if "shiny gold" in rules[rule]:
25
+ # containsGold[rule] = True
26
+ size = 0
27
+ while size != len (containsGold ):
28
+ size = len (containsGold )
29
+ for foundColor in list (containsGold ):
30
+ for newColor in rules :
31
+ if foundColor in rules [newColor ]:
32
+ containsGold [newColor ] = True
33
+ #print(size,"----------------",len(containsGold))
34
+ #print(containsGold.keys())
35
+ print (len (containsGold ) - 1 ) #remove shiny gold
36
+
37
+ #part 2
38
+ rules = {}
39
+ total = 0
40
+
41
+ def insidePackages (color ):
42
+ if len (rules [color ]) == 0 :
43
+ return 0
44
+ count = 0
45
+ for sub in rules [color ].keys ():
46
+ #print ("---",sub,rules[color][sub],insidePackages(sub))
47
+ count = count + (rules [color ][sub ] * (insidePackages (sub ) + 1 ))
48
+ #print(color,count)
49
+ return count
50
+
51
+
52
+ with open (fileName ) as file :
53
+ # text = file.readlines()
54
+ for rule in text :
55
+ total = total + 1
56
+ myColor = rule [0 :rule .find (" bag" )]
57
+ i = rule .find ("contain" ) + 7
58
+ others = rule [i :- 2 ]
59
+ others = others .replace ("bags" ,"" )
60
+ others = others .replace ("bag" ,"" )
61
+ others = others .split ("," )
62
+ contents = {}
63
+ for other in others :
64
+ try :
65
+ contents [other [3 :- 1 ]] = int (other [1 ])
66
+ except :
67
+ pass
68
+ rules [myColor ] = contents
69
+ #print(myColor,others)
70
+ #print(total, len(rules)) #proves rules are for unique colors
71
+
72
+ #print("------------")
73
+ #print(rules)
74
+ #print("------------")
75
+ insideGold = {}
76
+ for color in rules ["shiny gold" ]:
77
+ insideGold [color ] = rules ["shiny gold" ][color ]
78
+
79
+ #size = 0
80
+ #while size != len(insideGold):
81
+ # size = len(insideGold)
82
+ # for foundColor in list(insideGold):
83
+ # for newColor in rules[foundColor].keys():
84
+ # insideGold[newColor] = rules[foundColor][newColor]
85
+
86
+ #print(size,"----------------",len(containsGold))
87
+ #print(containsGold.keys())
88
+ packages = insidePackages ("shiny gold" )
89
+ #for item in insideGold.keys():
90
+ # packages = packages + insideGold[item]
91
+ print (packages )
0 commit comments