-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.py
executable file
·56 lines (37 loc) · 1.12 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
#!/usr/bin/env python3
# [Day 7: Handy Haversacks](https://adventofcode.com/2020/day/7)
import re
import sys
from pathlib import Path
verbose = "-v" in sys.argv
if verbose:
sys.argv.remove("-v")
filename = ("test.txt" if sys.argv[1] == "-t" else sys.argv[1]) if len(sys.argv) > 1 else "input.txt"
data = Path(filename).read_text().strip()
lines = data.splitlines()
bags = {}
for line in lines:
bag, contain = re.match(r"^(.+) bags contain (.+)\.$", line).groups()
contained = {}
for s in contain.split(","):
if s == "no other bags":
continue
n, sub_bag = re.match(r"^\s?(\d+) (.+) bags?$", s).groups()
contained[sub_bag] = int(n)
bags[bag] = contained
# part 1
def contains_color(bag, color):
for sub_bag in bags[bag]:
if sub_bag == color:
return True
if contains_color(sub_bag, color) is True:
return True
return False
print(sum(contains_color(bag, "shiny gold") for bag in bags))
# part 2
def count(bag):
t = 0
for s, n in bags[bag].items():
t += (count(s) + 1) * n
return t
print(count("shiny gold"))