-
Notifications
You must be signed in to change notification settings - Fork 2
/
pysolution.py
55 lines (42 loc) · 1.35 KB
/
pysolution.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
# SPDX-License-Identifier: BSD-3-Clause
with open('input') as f:
lines = [line.strip('.\n') for line in f.readlines()]
rules = {}
for line in lines:
bag, contains = line.split(' bags contain ')
contents = contains.split(', ')
contents_list = []
for content in contents:
if content == 'no other bags':
break
parts = content.split()
count = int(parts[0])
description = " ".join(parts[1:-1])
contents_list.append((count, description))
rules[bag] = contents_list
def contains_shiny_gold(bag):
contents = rules[bag]
for content in contents:
contained_bag = content[1]
if contained_bag == 'shiny gold':
return True
if contains_shiny_gold(contained_bag):
return True
return False
total = 0
for bag in rules.keys():
if contains_shiny_gold(bag):
total += 1
print(f'The answer to part 1 is {total}')
def contains_count(bag):
contents = rules[bag]
total = 0
for content in contents:
count, contained_bag = content
contained_count = contains_count(contained_bag)
# Add how many bags the contained bags contain
total += count * contained_count
# Add the contained bags themselves
total += count
return total
print(f"The answer to part 2 is {contains_count('shiny gold')}")