-
Notifications
You must be signed in to change notification settings - Fork 0
/
07.py
executable file
·55 lines (44 loc) · 1.31 KB
/
07.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
#!/usr/bin/env python3
import os
import sys
import re
import pprint
def get_input_file():
return os.path.basename(os.path.abspath(sys.argv[0])).strip(".py") + ".in"
def read_input(filename):
with open(filename, 'r') as f:
data = f.readlines();
return data;
def process(line):
rules = {}
last_match_len = 0
m = re.search("(?P<key>.*) bags contain ", line)
key = m.group('key')
line = line[len(m.group(0)):]
rules[key] = []
while(True):
m = re.search("(?P<count>\d+) (?P<color>[\w ]+) bag[s]*", line)
if (m):
rules[key].append( { "color" : m.group('color'), "count" : m.group('count') })
line = line[len(m.group(0)):]
else:
break;
return rules
def contains(bags, color, rules):
for bag in bags:
if 'shiny gold' == bag['color'] or contains(rules[bag['color']], color, rules):
return True
return False
def count(rules, color):
contains_color = []
for bag, subbags in rules.items():
if contains(subbags, color, rules):
contains_color.append(bag)
return contains_color
if __name__ == "__main__":
input_file = get_input_file();
input = read_input(input_file)
rules = {}
for i in input:
rules.update(process(i))
print(len(count(rules, "shiny gold")))