import re FIELDS = [ 'byr', # Birth Year 'iyr', # Issue Year 'eyr', # Expiration Year 'hgt', # Height 'hcl', # Hair Color 'ecl', # Eye Color 'pid', # Passport ID # 'cid', # Country ID ] def is_complete(entry): return all(f in entry for f in FIELDS) def validate_year(s, _min, _max): if not re.match('[0-9]{4}$', s): return False i = int(s) return i >= _min and i <= _max def validate_height(s): m = re.match('([0-9]+)(cm|in)$', s) if not m: return False value = int(m[1]) unit = m[2] if unit == 'cm': return value >= 150 and value <= 193 else: return value >= 59 and value <= 76 def validate_color(s): return re.match('#[0-9a-f]{6}$', s) def validate_eye_color(s): return s in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'] def validate_pid(s): return re.match('[0-9]{9}$', s) def is_valid(entry): return ( validate_year(entry['byr'], 1920, 2002) and validate_year(entry['iyr'], 2010, 2020) and validate_year(entry['eyr'], 2020, 2030) and validate_height(entry['hgt']) and validate_color(entry['hcl']) and validate_eye_color(entry['ecl']) and validate_pid(entry['pid']) # validate_pid(data['cid']) ) def parse(s): entry = {} for field in s.split(): key, value = field.split(':', 1) entry[key] = value return entry with open('input.txt') as fh: s = fh.read() entries = [parse(e) for e in s.split('\n\n')] print(len([e for e in entries if is_complete(e)])) print(len([e for e in entries if is_complete(e) and is_valid(e)]))