-
Notifications
You must be signed in to change notification settings - Fork 0
/
04.py
76 lines (62 loc) · 2.19 KB
/
04.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
69
70
71
72
73
74
75
76
import re
f = open('04.input', 'r')
data = [x.strip() for x in f.readlines()]
def part1(data):
valid_passport_count = 0
required_fields = ['byr' ,'iyr' ,'eyr' ,'hgt' ,'hcl' ,'ecl' ,'pid']
# Variable to track number of required fields for current passport
current = 0
for line in data:
if line == '': # Empty line indicates new passport
if current == len(required_fields):
valid_passport_count += 1
current = 0
continue
for field in line.split():
key, val = field.split(':')
if key in required_fields:
current += 1
return valid_passport_count
def valid(passport):
# Validate mandatory fields
fields = ['byr' ,'iyr' ,'eyr' ,'hgt' ,'hcl' ,'ecl' ,'pid']
for f in fields:
if(f not in passport):
return False
# Validate numerical
if not ( 1920 <= int(passport['byr']) <= 2002):
return False
if not ( 2010 <= int(passport['iyr']) <= 2020):
return False
if not ( 2020 <= int(passport['eyr']) <= 2030):
return False
# Validate Height
if 'cm' in passport['hgt'] and not (150 <= int(passport['hgt'][:-2]) <=193):
return False
elif 'in' in passport['hgt'] and not (59 <= int(passport['hgt'][:-2]) <= 76):
return False
if 'cm' not in passport['hgt'] and 'in' not in passport['hgt']:
return False
# Validate strings/enums
if passport['ecl'] not in ['amb', 'blu', 'brn','gry','grn','hzl','oth']:
return False
if re.match(r'^\#[0-9a-f]{6}$', passport['hcl']) is None:
return False
if re.match(r'^\d{9}$', passport['pid']) is None:
return False
return True
def part2(data):
valid_passport_count = 0
current = {}
for line in data:
if line == '':
if valid(current):
valid_passport_count += 1
current = {}
continue
for field in line.split():
field,val = field.split(':')
current[field] = val
return valid_passport_count
print "Part 1 solution: %d " % part1(data)
print "Part 2 solution: %d " % part2(data)