8 for rule in open("input.txt", "r"):
10 print("Rule: {}".format(rule))
11 m=re.match("^(.*?) bag(s|) contain (.*)$", rule)
14 contain=m.group(3).split(", ")
15 for contained in contain:
16 m2=re.match('^([0-9]*) (.*?) bag(s|).*$', contained)
18 bag_count=int(m2.group(1))
20 if not bag in contains:
22 contains[bag].append((bag_count, bag_name))
23 if not bag_name in contained_by:
24 contained_by[bag_name] = []
25 if not bag in contained_by[bag_name]:
26 contained_by[bag_name].append(bag)
28 looking_for="shiny gold"
31 for bag in contained_by[looking_for]:
38 new_bag_list=[b for b in bags]
41 for bag1 in new_bag_list:
42 if bag1 not in contained_by:
44 for bag2 in contained_by[bag1]:
46 new_new_bag_list.append(bag2)
48 if (len(new_new_bag_list) > 0):
49 new_bag_list=[b for b in new_new_bag_list]
56 print("Found {} bags that can contain {} bags".format(len(bags), looking_for))
58 def get_count(bag_name):
60 if not bag_name in contains:
62 for (num,bag) in contains[bag_name]:
63 count+=(get_count(bag)+1)*num
66 # now looking for how many bags in bags we're looking for
67 print("Contains {} bags".format(get_count(looking_for)))