import re def valid(ppt): k = ppt.keys() for v in ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]: if v not in k: print(f"Missing {v}.") return False # byr = ppt["byr"] # byrm = re.match(r"^(\d{4})$", byr) # if byrm == None: # print(f"Bad BYR: {byr}.") # return False # byrn = int(byrm[1]) # if byrn < 1920 or byrn > 2002: # print(f"Bad BYR: {byr}.") # return False # iyr = ppt["iyr"] # iyrm = re.match(r"^(\d{4})$", iyr) # if iyrm == None: # print(f"Bad IYR: {iyr}.") # return False # iyrn = int(iyrm[1]) # if iyrn < 2010 or iyrn > 2020: # print(f"Bad IYR: {iyr}.") # return False # eyr = ppt["eyr"] # eyrm = re.match(r"^(\d{4})$", eyr) # if eyrm == None: # print(f"Bad EYR: {eyr}.") # return False # eyrn = int(eyrm[1]) # if eyrn < 2020 or eyrn > 2030: # print(f"Bad EYR: {eyr}.") # return False # hgt = ppt["hgt"] # hgtm = re.match(r"^(\d{2,3})(cm|in)$", hgt) # if hgtm == None: # print(f"Bad HGT: {hgt}.") # return False # hgtn = int(hgtm[1]) # hgtu = hgtm[2] # if (hgtu == "cm" and (hgtn < 150 or hgtn > 193)) or (hgtu == "in" and (hgtn < 59 or hgtn > 76)): # print(f"Bad HGT: {hgt}.") # return False # hcl = ppt["hcl"] # if re.search(r"^#[0-9a-f]{6}$", hcl) == None: # print(f"Bad HCL: {hcl}.") # return False # ecl = ppt["ecl"] # if ecl not in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]: # print(f"Bad ECL: {ecl}.") # return False # pid = ppt["pid"] # if re.search(r"^[0-9]{9}$", pid) == None: # print(f"Bad PID: {pid}.") # return False return True def main(): with open("input4.txt") as file: text = file.read() ppts = text.split("\n\n") print(f"I have {len(ppts)} passports.") count = 0 cinv = 0 for ppt in ppts: ppt = ppt.replace("\n", " ") pptchunks = ppt.split(" ") pptdct = {} for chunk in pptchunks: try: bits = chunk.split(":") pptdct[bits[0]] = bits[1] except: print(ppt) # print(ppt) # print(pptdct) if valid(pptdct): count += 1 else: cinv += 1 print(f"There are {count} valid passports and {cinv} invalid ones.") if __name__ == "__main__": main()