-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathday_7.py
68 lines (53 loc) · 2 KB
/
day_7.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
#!/bin/env python
""" Advent of Code Day 7 """
import re
from collections import deque
from functools import cache
class Day7:
""" Class for processing of day 7 """
def __init__(self):
self.all_lines = ()
self.all_bags = {}
def load_input(self, file_name):
""" Load the input file """
with open(file_name, "r") as in_file:
self.all_lines = [line.rstrip('\n') for line in in_file]
def process_lines(self):
""" Process all lines, load the mapping """
for line in self.all_lines:
container_re = re.compile(r'(.*?) bags')
bags_re = re.compile(r'(?:(\d+)|no other) (.*?) bags*')
container_name = re.match(container_re, line).group(1)
bags = re.findall(bags_re, line)
self.all_bags[container_name] = bags
def get_task1(self):
""" Find all bags that contain the golden one """
gold_containers = set()
queue = deque()
queue.append('shiny gold')
while queue:
test_name = queue.pop()
for container_name, items in self.all_bags.items():
for _, bag in items:
if test_name in bag:
queue.append(container_name)
gold_containers.add(container_name)
return len(gold_containers)
@cache
def count_containers(self, container_name):
""" Recursively count the containers """
count = 1
for name, items in self.all_bags.items():
if container_name in name:
for bag_count, bag in items:
count += int(bag_count) * self.count_containers(bag)
return count
def get_task2(self):
""" Count all bags within the shiny gold one """
return self.count_containers('shiny gold') - 1
if __name__ == "__main__":
day7 = Day7()
day7.load_input("input7")
day7.process_lines()
print(f"Task1: {day7.get_task1()}")
print(f"Task2: {day7.get_task2()}")