2020aoc/day4.py

71 lines
1.7 KiB
Python

import re
passports = []
with open('day4/input') as reader:
cur = ''
for line in reader.read().splitlines():
if line != '':
if cur == '':
cur += line
else:
cur += ' ' + line
else:
passports.append(cur)
cur = ''
if cur != '':
passports.append(cur)
def byr(s):
return re.match('^\d{4}$', s) is not None and (1920 <= int(s) <= 2002)
def iyr(s):
return re.match('^\d{4}$', s) is not None and (2010 <= int(s) <= 2020)
def eyr(s):
return re.match('^\d{4}$', s) is not None and (2020 <= int(s) <= 2030)
def hgt(s):
return (re.match('^\d+cm$', s) is not None and (150 <= int(s[:-2]) <= 193)) \
or (re.match('^\d+in$', s) is not None and (59 <= int(s[:-2]) <= 76))
def hcl(s):
return re.match('^#[0-9a-f]{6}$', s) is not None
def ecl(s):
return s in {'amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'}
def pid(s):
return re.match('^[0-9]{9}$', s) is not None
verify = {'byr': byr,
'iyr': iyr,
'eyr': eyr,
'hgt': hgt,
'hcl': hcl,
'ecl': ecl,
'pid': pid,
'cid': lambda s: True
}
valid = set(verify.keys())
count_valids = 0
for p in passports:
props = set()
failed = False
for prop in p.split(' '):
key, value = prop.split(':')
props.add(key)
if not verify[key](value):
failed = True
break
if failed:
continue
missing = valid.difference(props)
if missing == set() or missing == {'cid'}:
count_valids += 1
print(count_valids)