adventofcode-2020/04/part2

67 lines
1.5 KiB
Plaintext
Raw Normal View History

2020-12-13 15:34:03 +01:00
#!/usr/bin/python3
import re
def byr_valid(s):
try:
yr = int(s)
return 1920 <= yr <= 2002
except:
return False
def iyr_valid(s):
try:
yr = int(s)
return 2010 <= yr <= 2020
except:
return False
def eyr_valid(s):
try:
yr = int(s)
return 2020 <= yr <= 2030
except:
return False
def hgt_valid(s):
try:
m = re.fullmatch(r"(\d+)(cm|in)", s)
if m.group(2) == "cm":
return 150 <= int(m.group(1)) <= 193
elif m.group(2) == "in":
return 59 <= int(m.group(1)) <= 76
else:
return False
except:
return False
def hcl_valid(s):
return bool(re.fullmatch(r"#[0-9a-f]{6}", s))
def ecl_valid(s):
return s in ("amb", "blu", "brn", "gry", "grn", "hzl", "oth")
def pid_valid(s):
return bool(re.fullmatch(r"[0-9]{9}", s))
checks = {
"byr": byr_valid, "iyr": iyr_valid, "eyr": eyr_valid,
"hgt": hgt_valid, "hcl": hcl_valid, "ecl": ecl_valid,
"pid": pid_valid,}
valid_count = 0
with open("input") as fh:
all_data = fh.read()
passport_strings = all_data.split("\n\n")
for ps in passport_strings:
fields = ps.split()
passport = {}
for f in fields:
k, v = f.split(":")
passport[k] = v
is_valid = True
for f, c in checks.items():
is_valid = is_valid and f in passport and c(passport[f])
valid_count += is_valid
print(valid_count)