-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day7.py
97 lines (71 loc) · 2.79 KB
/
Day7.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
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
path = "./Inputs/day7.txt"
# path = "./Inputs/day7Test.txt"
# path = "./Inputs/day7Test2.txt"
# path = "./Inputs/day7Test3.txt"
allBagsPt1 = {}
allBagsPt2 = {}
def part1():
count = 0
with open(path) as file:
# build a dictionary to hold all values; key = outer bag, value = list of inner bags
for line in file.readlines():
line = line.rstrip('s.\n')
# massage the string to get each colored bag mentioned
splits = line.split('bag') # split line on word 'bag'
splits = list(map(str.strip, splits))
splits = list(filter(None, splits))
allBagsPt1[splits[0]] = [] # add the dict key (outer bag)
# add inner bags as dict values
for bag in splits[1:]: # skip first which was the key
bagColor = bag.split()[-2:] # inner bag color is last 2 words
name = " ".join(map(str, bagColor))
allBagsPt1[splits[0]].append(name)
for mainBag in allBagsPt1:
if containsBag(mainBag):
count += 1
print("Part 1:")
print(count)
def part2():
count = 0
with open(path) as file:
# build a dictionary to hold all values; key = outer bag, value = list of inner bags
for line in file.readlines():
line = line.rstrip('s.\n')
# massage the string to get each colored bag mentioned
splits = line.split('bag') # split line on word 'bag'
splits = list(map(str.strip, splits))
splits = list(filter(None, splits))
allBagsPt2[splits[0]] = [] # add the dict key (outer bag)
# add inner bags as dict values
for bag in splits[1:]: # skip first which was the key
bagColor = bag.split()[-3:] # amount + color = last 3 words
name = " ".join(map(str, bagColor))
allBagsPt2[splits[0]].append(name)
count = countBags('shiny gold')
print("Part 2:")
print(count)
# Part1
# checks bags until a 'shiny gold' bag is found
def containsBag(bag):
if 'shiny gold' in allBagsPt1[bag]:
return True
else:
for childBag in allBagsPt1[bag]:
if childBag != 'no other':
found = containsBag(childBag)
if found:
return True
# Part2
# counts bags within passed bag
def countBags(bag):
if 'no' in allBagsPt2[bag][0]:
return 0
# child bag count
count = 0
for childBag in allBagsPt2[bag]:
numBags = int(childBag.split(' ', 1)[0])
color = " ".join(map(str, childBag.split()[-2:]))
count += numBags + (numBags * countBags(color))
return count
part1()
part2()