4.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. passports = []
  2. with open("4.input") as f:
  3. passport = {}
  4. for line in f.readlines():
  5. if line.strip() == "":
  6. passports.append(passport)
  7. passport = {}
  8. else:
  9. pairs = line.strip().split(" ")
  10. for pair in pairs:
  11. [key, value] = pair.strip().split(":")
  12. passport[key] = value
  13. passports.append(passport)
  14. def passport_valid(passport):
  15. required_fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
  16. for key in required_fields:
  17. if key not in passport.keys():
  18. return False
  19. return True
  20. def passport_valid_extended(passport):
  21. if not passport_valid(passport):
  22. return False
  23. byr = int(passport["byr"])
  24. if byr not in range(1920, 2003):
  25. return False
  26. iyr = int(passport["iyr"])
  27. if iyr not in range(2010, 2021):
  28. return False
  29. eyr = int(passport["eyr"])
  30. if eyr not in range(2020, 2031):
  31. return False
  32. hgt = passport["hgt"]
  33. if "cm" in hgt:
  34. if int(hgt[0:-2]) not in range(150, 194):
  35. return False
  36. elif "in" in hgt:
  37. if int(hgt[0:-2]) not in range(59, 77):
  38. return False
  39. else:
  40. return False
  41. hcl = passport["hcl"]
  42. if hcl[0] != '#':
  43. return False
  44. if len(hcl) != 7:
  45. return False
  46. for c in hcl[1:6]:
  47. if c not in "0123456789abcdef":
  48. return False
  49. if passport["ecl"] not in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]:
  50. return False
  51. pid = passport["pid"]
  52. if len(pid) != 9:
  53. return False
  54. for c in pid:
  55. if c not in "0123456789":
  56. return False
  57. return True
  58. valid = filter(passport_valid, passports)
  59. print(sum(1 for _ in valid))
  60. valid = filter(passport_valid_extended, passports)
  61. print(sum(1 for _ in valid))