-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday7.py
More file actions
98 lines (79 loc) · 2.59 KB
/
day7.py
File metadata and controls
98 lines (79 loc) · 2.59 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import re
lines = open('day7-input.txt').readlines()
# lines = open('example.txt').readlines()
def cleanStr(rule):
rule = rule.strip()
if 'contains' in rule:
return rule.split('contains ')
else:
return rule.split('contain ')
def removeCount(bag_desc):
return re.sub('\d+', '', bag_desc)
def findOuterBag(s):
match = re.search(r'^(.*?) bags', s)
if match:
return match.group(1)
else:
return match
def findInnerBags(s):
return re.search(r'\d+ (.*?) bag', s).group(1)
print(findInnerBags('5 dark green bags'))
print(findInnerBags('5 light gray bags'))
print(findOuterBag('light beighe bags contain'))
def solveDay7():
bag_rules = {}
for rule in lines:
bags = rule.split('contain ')
outer_bag = findOuterBag(bags[0])
inner_bags = []
if 'no other bags' not in bags[1]:
for b in bags[1].split(', '):
inner_bags.append(findInnerBags(b))
# the bags that can contain these bags
for bag in inner_bags:
if bag in bag_rules:
bag_rules[bag].append(outer_bag)
else:
bag_rules[bag] = [outer_bag]
solution = set()
to_traverse = bag_rules['shiny gold']
while len(to_traverse) > 0:
last_el = to_traverse.pop()
solution.add(last_el)
if last_el in bag_rules:
to_traverse += bag_rules[last_el]
return solution
def findInnerBagsWithCount(s):
match = re.search(r'(\d+) (.*?) bag', s)
return [match.group(1), match.group(2)]
def solveDay7Part2():
bag_rules = {}
for rule in lines:
bags = rule.split('contain ')
outer_bag = findOuterBag(bags[0])
inner_bags = []
if 'no other bags' not in bags[1]:
for b in bags[1].split(', '):
inner_bags.append(findInnerBagsWithCount(b))
bag_rules[outer_bag] = inner_bags
solution = 0
bag_count = {}
to_traverse = bag_rules['shiny gold']
while len(to_traverse) > 0:
count, bag_name = to_traverse.pop()
if bag_name in bag_count:
bag_count[bag_name] += int(count)
else:
bag_count[bag_name] = int(count)
solution += int(count)
if bag_name in bag_rules:
children = bag_rules[bag_name]
total_children = []
for c, n in children:
total_children.append([int(count) * int(c), n])
to_traverse += total_children
other_count = 0
for k, v in bag_count.items():
other_count += v
return solution
print(solveDay7Part2())