You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

day4b.py 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import re
  2. def valid(ppt):
  3. k = ppt.keys()
  4. for v in ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]:
  5. if v not in k:
  6. print(f"Missing {v}.")
  7. return False
  8. byr = ppt["byr"]
  9. byrm = re.match(r"^(\d{4})$", byr)
  10. if byrm == None:
  11. print(f"Bad BYR: {byr}.")
  12. return False
  13. byrn = int(byrm[1])
  14. if byrn < 1920 or byrn > 2002:
  15. print(f"Bad BYR: {byr}.")
  16. return False
  17. iyr = ppt["iyr"]
  18. iyrm = re.match(r"^(\d{4})$", iyr)
  19. if iyrm == None:
  20. print(f"Bad IYR: {iyr}.")
  21. return False
  22. iyrn = int(iyrm[1])
  23. if iyrn < 2010 or iyrn > 2020:
  24. print(f"Bad IYR: {iyr}.")
  25. return False
  26. eyr = ppt["eyr"]
  27. eyrm = re.match(r"^(\d{4})$", eyr)
  28. if eyrm == None:
  29. print(f"Bad EYR: {eyr}.")
  30. return False
  31. eyrn = int(eyrm[1])
  32. if eyrn < 2020 or eyrn > 2030:
  33. print(f"Bad EYR: {eyr}.")
  34. return False
  35. hgt = ppt["hgt"]
  36. hgtm = re.match(r"^(\d{2,3})(cm|in)$", hgt)
  37. if hgtm == None:
  38. print(f"Bad HGT: {hgt}.")
  39. return False
  40. hgtn = int(hgtm[1])
  41. hgtu = hgtm[2]
  42. if (hgtu == "cm" and (hgtn < 150 or hgtn > 193)) or (hgtu == "in" and (hgtn < 59 or hgtn > 76)):
  43. print(f"Bad HGT: {hgt}.")
  44. return False
  45. hcl = ppt["hcl"]
  46. if re.search(r"^#[0-9a-f]{6}$", hcl) == None:
  47. print(f"Bad HCL: {hcl}.")
  48. return False
  49. ecl = ppt["ecl"]
  50. if ecl not in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]:
  51. print(f"Bad ECL: {ecl}.")
  52. return False
  53. pid = ppt["pid"]
  54. if re.search(r"^[0-9]{9}$", pid) == None:
  55. print(f"Bad PID: {pid}.")
  56. return False
  57. return True
  58. def main():
  59. with open("input4.txt") as file:
  60. text = file.read()
  61. ppts = text.split("\n\n")
  62. print(f"I have {len(ppts)} passports.")
  63. count = 0
  64. cinv = 0
  65. for ppt in ppts:
  66. ppt = ppt.replace("\n", " ")
  67. pptchunks = ppt.split(" ")
  68. pptdct = {}
  69. for chunk in pptchunks:
  70. if chunk != "":
  71. bits = chunk.split(":")
  72. pptdct[bits[0]] = bits[1]
  73. if valid(pptdct):
  74. count += 1
  75. else:
  76. cinv += 1
  77. print(f"There are {count} valid passports and {cinv} invalid ones.")
  78. if __name__ == "__main__":
  79. main()