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
|
#!/usr/bin/env python
from collections import defaultdict
import re
target = {
'children': 3,
'cats': 7,
'samoyeds': 2,
'pomeranians': 3,
'akitas': 0,
'vizslas': 0,
'goldfish': 5,
'trees': 3,
'cars': 2,
'perfumes': 1
}
info_re = re.compile(r'(\w+): (\d)')
# part 1
with open('day16.txt') as data:
for num, line in enumerate(data):
current = dict(map(lambda x: (x[0], int(x[1])), info_re.findall(line)))
if all(target[key] == current[key] for key in current):
print(num+1)
break
# part 2
def valid(curr):
for key in curr:
if key == 'cats' or key == 'trees':
yield curr[key] > target[key]
elif key == 'pomeranians' or key == 'goldfish':
yield curr[key] < target[key]
else:
yield curr[key] == target[key]
with open('day16.txt') as data:
for num, line in enumerate(data):
current = dict(map(lambda x: (x[0], int(x[1])), info_re.findall(line)))
if all(valid(current)):
print(num+1)
break
|