From e63eab257f956639b7fcef84cfb134501c328687 Mon Sep 17 00:00:00 2001 From: dece Date: Fri, 4 Dec 2020 15:52:56 +0100 Subject: [PATCH] Day 4 --- 2020/day4.py | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 2020/day4.py diff --git a/2020/day4.py b/2020/day4.py new file mode 100644 index 0000000..d5ae18b --- /dev/null +++ b/2020/day4.py @@ -0,0 +1,63 @@ +import re +import string + + +REQ = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"] + + +def main(): + with open("day4.txt", "rt") as f: + lines = [line.rstrip() for line in f.readlines()] + passports = get_passports(lines) + + # Part 1 + num_valids = 0 + for passport in passports: + if all(k in passport for k in REQ): + num_valids += 1 + print("Valids:", num_valids) + + # Part 2 + num_valids = 0 + hair_re = re.compile(r"#[abcdef\d]{6}") + for passport in passports: + if not all(k in passport for k in REQ): + continue + if not (1920 <= int(passport["byr"]) <= 2002): + continue + if not (2010 <= int(passport["iyr"]) <= 2020): + continue + if not (2020 <= int(passport["eyr"]) <= 2030): + continue + if not ( + (passport["hgt"].endswith("cm") and 150 <= int(passport["hgt"][:-2]) <= 193) + or (passport["hgt"].endswith("in") and 59 <= int(passport["hgt"][:-2]) <= 76) + ): + continue + if not hair_re.match(passport["hcl"]): + continue + if not passport["ecl"] in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]: + continue + if not (len(passport["pid"]) == 9 and all(c in string.digits for c in passport["pid"])): + continue + num_valids += 1 + print("P2 valids:", num_valids) + + +def get_passports(lines): + passports = [] + passport = {} + for line in lines: + elements = line.split() + for element in elements: + k, v = element.split(":") + passport[k] = v + if not line: + passports.append(passport) + passport = {} + passports.append(passport) + return passports + + +if __name__ == "__main__": + main()