#advent of code 2020 #day 04 import re PuzzleInput = open("04.in","r").read() passports = PuzzleInput.split("\n\n"); p1 = 0; p2 = 0; documents = dict(); required = ["byr","iyr","eyr","hgt","hcl","ecl","pid"]; #puzzle description def part2(doc): valid2 = True; valid2 *= len(doc["byr"]) == 4 and int(doc["byr"]) >= 1920 and int(doc["byr"]) <= 2002; valid2 *= len(doc["iyr"]) == 4 and int(doc["iyr"]) >= 2010 and int(doc["iyr"]) <= 2020; valid2 *= len(doc["eyr"]) == 4 and int(doc["eyr"]) >= 2020 and int(doc["eyr"]) <= 2030; valid2 *= doc["hgt"][-2:] == "cm" or doc["hgt"][-2:] == "in"; if doc["hgt"][-2:] == "cm": valid2 *= int(doc["hgt"][:-2]) >= 150 and int(doc["hgt"][:-2]) <= 193; if doc["hgt"][-2:] == "in": valid2 *= int(doc["hgt"][:-2]) >= 59 and int(doc["hgt"][:-2]) <= 76; valid2 *= doc["hcl"][0] == "#"; valid2 *= len(re.findall("[a-f]|[0-9]",doc["hcl"])) == 6; valid2 *= doc["ecl"] in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]; valid2 *= len(doc["pid"]) == 9; return valid2; for i,p in enumerate(passports): p = p.replace("\n"," ") documents[i] = dict(); for entry in p.split(" "): if len(entry) == 0: continue; k,v = entry.split(":"); documents[i][k] = v; valid = True; for req in required: valid *= req in documents[i]; p1 += 1*valid; if valid: p2 += 1*part2(documents[i]); print("part 1 =",p1); print("part 2 =",p2);