-
Notifications
You must be signed in to change notification settings - Fork 0
/
7.2.py
57 lines (49 loc) · 1.19 KB
/
7.2.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import re
with open('input/7.txt') as f:
content = f.readlines()
bags = {}
empty = {}
for line in content:
rule = {}
r = re.search(r'^(\w+|\w+ \w+) bag', line)
r2 = re.search(r'contain (.*)', line)
colour = r.group(1)
contents = r2.group(1).replace('.', '').split(',')
contents = [c.replace(' bags', '').replace(' bag', '').strip() for c in contents]
if 'no other' in contents:
bags[colour] = []
continue
# print(contents)
bags[colour] = contents
sorted_items = sorted(bags.items(), key = lambda item : len(item[1]))
counts = {}
for bag in sorted_items:
if not bag[1]:
counts[bag[0]] = 1
sorted_items.remove(bag)
def contains(colour):
c = bags[colour]
if not c:
return 'Empty'
s = ''
for i in c:
r = re.search(r'(\d+) (.*)', i)
n = int(r.group(1))
c = r.group(2)
s += str(n) + ' ' + c + ', '
s = re.sub(r', $', '', s)
return s
print(contains('shiny gold'))
def count(colour):
contains = bags[colour]
if not contains:
return 1
total = 0
for i in contains:
r = re.search(r'(\d+) (.*)', i)
n = r.group(1)
c = r.group(2)
total += int(n)*count(c)
return total+1
c = 'shiny gold'
print(c, ':', contains(c), count(c)-1)