This repository was archived by the owner on Feb 19, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday4.py
More file actions
105 lines (79 loc) · 2.55 KB
/
day4.py
File metadata and controls
105 lines (79 loc) · 2.55 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env python3
import re
filename = 'inputs/input4.txt'
fields = ['byr', 'iyr', 'hgt', 'eyr',
'hcl', 'ecl', 'pid']
def is_valid_birth_year(year):
try:
year = int(year)
return year >= 1920 and year <= 2002
except ValueError:
return False
def is_valid_issue_year(year):
try:
year = int(year)
return year >= 2010 and year <= 2020
except ValueError:
return False
def is_valid_expiration_year(year):
try:
year = int(year)
return year >= 2020 and year <= 2030
except ValueError:
return False
def is_valid_height(hgt):
try:
measure = hgt[-2:]
height = int(hgt[:-2])
if measure == 'cm':
return height >= 150 and height <= 193
elif measure == 'in':
return height >= 59 and height <= 76
else:
return False
except ValueError:
return False
def is_valid_hair_color(color):
hair_color_pattern = re.compile('^#[a-z0-9]+$')
return hair_color_pattern.match(color) is not None
def is_valid_eye_color(color):
colors = ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']
return color in colors
def is_valid_passport_id(pid):
pid_pattern = re.compile('^(\d){9}$')
return pid_pattern.match(pid) is not None
def is_valid_passport(passport):
for field in fields:
if field not in passport:
return False
return True
def is_valid_passport_p2(passport):
try:
return is_valid_birth_year(passport['byr']) and \
is_valid_issue_year(passport['iyr']) and \
is_valid_expiration_year(passport['eyr']) and \
is_valid_height(passport['hgt']) and \
is_valid_hair_color(passport['hcl']) and \
is_valid_eye_color(passport['ecl']) and \
is_valid_passport_id(passport['pid'])
except KeyError:
return False
if __name__ == '__main__':
with open(filename, 'r') as fin:
lines = fin.read().split('\n')
valid_passports = 0
valid_passports_p2 = 0
passport = dict()
for line in lines:
if len(line.strip()):
for attr in line.split(' '):
attr, val = attr.split(':')
passport[attr] = val
else:
if is_valid_passport(passport):
valid_passports += 1
if is_valid_passport_p2(passport):
valid_passports_p2 += 1
passport = dict()
print(f'Valid Passports: {valid_passports}')
print(f'Valid Passports Part 2: {valid_passports_p2}')