-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday04.py
53 lines (46 loc) · 1.63 KB
/
day04.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
import re
def parse(lines):
passports = []
passport = {}
for line in lines:
if line == '':
passports.append(passport)
passport = {}
else:
for field in line.split():
key, val = field.split(':')
if key != 'cid':
passport[key] = val
passports.append(passport)
return passports
def has_required_fields(passport):
required_fields = set(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'])
return set(passport.keys()) == required_fields
def is_valid(p):
byr=p['byr']; iyr=p['iyr']; eyr=p['eyr']
hgt=p['hgt']; hcl=p['hcl']; ecl=p['ecl']
pid=p['pid']
return \
len(byr) == 4 and 1920 <= int(byr) <= 2002 and \
len(iyr) == 4 and 2010 <= int(iyr) <= 2020 and \
len(eyr) == 4 and 2020 <= int(eyr) <= 2030 and \
(hgt[-2:]=='cm' and 150 <= int(hgt[:-2]) <= 193 or \
hgt[-2:]=='in' and 59 <= int(hgt[:-2]) <= 76) and \
len(hcl) == 7 and hcl[0] == '#' and \
ecl in ('amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth') and \
len(pid) == 9 and re.match(r'[0-9]', pid) is not None
def part1(passports):
return len([p for p in passports if has_required_fields(p)])
def part2(passports):
return len([p for p in passports if has_required_fields(p) and is_valid(p)])
def main(inp):
with open(inp) as f:
lines = f.read().splitlines()
passports = parse(lines)
res1 = part1(passports)
res2 = part2(passports)
return res1, res2
if __name__ == '__main__':
a, b = main('../input/input04.txt')
print('day04.1:', a)
print('day04.2:', b)