04_passport.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/env python3
  2. import re
  3. import sys
  4. def parse(f):
  5. cur = {}
  6. for line in f:
  7. if line == '\n':
  8. yield cur
  9. cur = {}
  10. else:
  11. for pair in line.rstrip().split():
  12. key, val = pair.split(':')
  13. cur[key] = val
  14. if cur:
  15. yield cur
  16. required = ('byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid')
  17. def valid_basic(pp):
  18. return all(key in pp for key in required)
  19. def valid_strict(pp):
  20. def isnum(key, lo, hi, suffix=''):
  21. val = pp[key]
  22. if not val.endswith(suffix):
  23. return False
  24. val = val[:len(val) - len(suffix)]
  25. return val.isdigit() and lo <= int(val) <= hi
  26. return valid_basic(pp) and \
  27. isnum('byr', 1920, 2002) and \
  28. isnum('iyr', 2010, 2020) and \
  29. isnum('eyr', 2020, 2030) and \
  30. (isnum('hgt', 150, 193, 'cm') or isnum('hgt', 59, 76, 'in')) and \
  31. re.match(r'#[0-9a-f]{6}$', pp['hcl']) is not None and \
  32. pp['ecl'] in ('amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth') and \
  33. re.match(r'\d{9}$', pp['pid']) is not None
  34. passports = list(parse(sys.stdin))
  35. print(sum(map(valid_basic, passports)))
  36. print(sum(map(valid_strict, passports)))