master
1import pprint
2import re
3
4def read_input():
5 with open("input/d04p1.txt") as f:
6 content = f.read()
7 content_split = re.split(r"(?:\r?\n){2,}", content.strip())
8 lines = [line.replace("\n", " ") for line in content_split]
9 return lines
10
11
12def parse(line):
13 attrs = line.split(" ")
14 passport = {k:v for (k,v) in [tuple(attr.split(":")) for attr in attrs]}
15 return passport
16
17def valid_p1(passport):
18 if not 'byr' in passport.keys(): return 0
19 if not 'iyr' in passport.keys(): return 0
20 if not 'eyr' in passport.keys(): return 0
21 if not 'hgt' in passport.keys(): return 0
22 if not 'hcl' in passport.keys(): return 0
23 if not 'ecl' in passport.keys(): return 0
24 if not 'pid' in passport.keys(): return 0
25 #if not 'cid' in passport.keys(): return False
26 return 1
27
28def valid_p2(passport):
29
30 if not 'byr' in passport.keys(): return 0
31 byr = int(passport['byr'])
32 if 2002 < byr or byr < 1920: return 0
33
34 if not 'iyr' in passport.keys(): return 0
35 iyr = int(passport['iyr'])
36 if 2020 < iyr or iyr < 2010: return 0
37
38 if not 'eyr' in passport.keys(): return 0
39 eyr = int(passport['eyr'])
40 if 2030 < eyr or eyr < 2020: return 0
41
42 if not 'hgt' in passport.keys(): return 0
43 hgt = passport['hgt']
44 if not ("cm" in hgt or "in" in hgt): return 0
45 if "cm" in hgt:
46 hgt_cm = int(hgt.split("c")[0])
47 if 193 < hgt_cm or hgt_cm < 150: return 0
48 if "in" in hgt:
49 hgt_in = int(hgt.split("i")[0])
50 if 76 < hgt_in or hgt_in < 59: return 0
51
52 if not 'hcl' in passport.keys(): return 0
53 hcl = passport['hcl']
54 match = re.match(r'#[0-9,a-z]{6}', hcl)
55 if match == None: return 0
56 if not (match.start()==0 and match.end()==len(hcl)): return 0
57
58 if not 'ecl' in passport.keys(): return 0
59 ecl = passport['ecl']
60 valid_ecls = ['amb','blu','brn','gry','grn','hzl','oth']
61 if ecl not in valid_ecls: return 0
62
63 if not 'pid' in passport.keys(): return 0
64 pid = passport['pid']
65 match = re.match(r'[0-9]{9}', pid)
66 if match == None: return 0
67 if not (match.start()==0 and match.end()==len(pid)): return 0
68
69 #if not 'cid' in passport.keys(): return False
70 return 1
71
72input_lines = read_input()
73parsed_lines = [parse(line) for line in input_lines]
74p1_valid = sum([valid_p1(passport) for passport in parsed_lines])
75p2_valid = sum([valid_p2(passport) for passport in parsed_lines])
76print("p1:", p1_valid)
77print("p2:", p2_valid)