2.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. def validate_int(value, mi, ma):
  2. value = int(value)
  3. return mi <= value <= ma
  4. def validate_height(value):
  5. v = int(value[:-2])
  6. t = value[-2:]
  7. if (t == "cm" and 150<=v<=193) or (t == "in" and 59<=v<=76):
  8. return True
  9. return False
  10. def validate_hex(h):
  11. return h[0] == "#" and len(h[1:]) == 6 and is_int(h[1:], base=16)
  12. def is_int(x, base=10):
  13. try:
  14. int(x, base=base)
  15. except ValueError:
  16. return False
  17. return True
  18. validators = {
  19. 'byr': lambda x: validate_int(x, 1920, 2002),
  20. 'iyr': lambda x: validate_int(x, 2010, 2020),
  21. 'eyr': lambda x: validate_int(x, 2020, 2030),
  22. 'hgt': lambda x: validate_height(x),
  23. 'hcl': lambda x: validate_hex(x),
  24. 'ecl': lambda x: x in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'],
  25. 'pid': lambda x: len(x) == 9 and is_int(x)
  26. }
  27. def validate(entry, required_fields):
  28. for field in required_fields:
  29. if field not in entry or not validators[field](entry[field]):
  30. return False
  31. return True
  32. entries = [{}]
  33. index = 0
  34. with open("input") as f:
  35. for line in f:
  36. line = line.strip()
  37. if not line:
  38. entries.append({})
  39. index = index + 1
  40. else:
  41. for entry in line.split(" "):
  42. key, value = entry.split(":")
  43. entries[index][key] = value
  44. required = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
  45. print(list(map(lambda x: validate(x, required), entries)).count(True))