33 lines
1.2 KiB
Python
33 lines
1.2 KiB
Python
import re
|
|
|
|
def read_file():
|
|
passports = []
|
|
with open("input.txt","r") as f:
|
|
raw_passports = f.read().strip().split('\n\n')
|
|
for passport in raw_passports:
|
|
parts = re.split('\s', passport)
|
|
passport_dict = dict(part.split(':') for part in parts) # use dictionary comprehension
|
|
passports.append(passport_dict)
|
|
return passports
|
|
|
|
validators = {
|
|
'byr': lambda x: len(x) == 4 and 2002 >= int(x) >= 1920,
|
|
'iyr': lambda x: len(x) == 4 and 2020 >= int(x) >= 2010,
|
|
'eyr': lambda x: len(x) == 4 and 2030 >= int(x) >= 2020,
|
|
'hgt': lambda x: (x[-2:] == 'cm' and 150 <= int(x[:-2]) <= 193) or (x[-2:] == 'in' and 59 <= int(x[:-2]) <= 76),
|
|
'hcl': lambda x: re.match('^#[\da-f]{6}$', x) != None,
|
|
'ecl': lambda x: x in ['amb','blu','brn','gry','grn','hzl','oth'],
|
|
'pid': lambda x: len(x) == 9 and x.isdigit(),
|
|
}
|
|
|
|
def main():
|
|
part1 = part2 = 0
|
|
passports = read_file()
|
|
for passport in passports:
|
|
if all(key in passport for key in validators): # TIL all() checks for iterable conditions
|
|
part1 += 1
|
|
if all(validators[key](passport[key]) for key in validators): # apply validators as function
|
|
part2 += 1
|
|
print(f'{part1=} {part2=}')
|
|
if __name__ == "__main__":
|
|
main() |