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.
 
 

78 lines
2.6 KiB

import re
# Valid Passport if all fields on it
def valid_passport(line):
# Must contain "byr:", "pid:", "iyr:". "eyr:", "hgt:" "hcl:" und "ecl:"
contains = ["byr:", "pid:", "iyr:", "eyr:", "hgt:", "hcl:", "ecl:"]
return all(i in line for i in contains)
# Bene's function for height
def valid_height(height):
match = re.compile(r"(\d+)(cm|in)").search(height)
if match is None: return False
num, unit = match.groups()
if unit == 'cm': return 150 <= int(num) <= 193
if unit == 'in': return 59 <= int(num) <= 76
return False
# Valid passport if fields also contain fitting values
def valid_passport2(line):
# Must contain "byr:", "pid:", "iyr:". "eyr:", "hgt:" "hcl:" und "ecl:"
contains = ["byr:", "pid:", "iyr:", "eyr:", "hgt:", "hcl:", "ecl:"]
if all(i in line for i in contains):
groups = re.compile(r"(?P<key>\w+):(?P<value>\S+)")
for (key, value) in groups.findall(line):
if key == "byr":
if not (len(value) == 4 and (1920 <= int(value) <= 2002)):
return False
elif key == "iyr":
if not (len(value) == 4 and (2010 <= int(value) <= 2020)):
return False
elif key == "eyr":
if not (len(value) == 4 and (2020 <= int(value) <= 2030)):
return False
elif key == "hgt":
pattern1 = re.compile(r"(1[5-8][0-9]|19[0-3])cm")
pattern2 = re.compile(r"(59|6[0-9]|7[0-6])in")
if not valid_height(value):
return False
elif key == "hcl":
pattern = re.compile(r"#([0-9]|[a-f]){6}")
if not pattern.match(value):
return False
elif key == "ecl":
if value not in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]:
return False
elif key == "pid":
pattern = re.compile(r"\d{9}")
if not (pattern.match(value) and len(value) == 9):
return False
else:
if not key == "cid":
return False
return True
return False
with open(r"C:\Users\Maya\Desktop\Uni\WS_2021\AoC\input04") as f:
lines = f.read()
lines = lines.replace("\n\n", '\t').replace("\n", " ").split("\t")
sum(valid_passport(p) for p in lines)
# count for challenge 1
count = 0
for l in lines:
if valid_passport(l):
count += 1
print(count)
# count for challenge 2
count2 = 0
for l in lines:
if valid_passport2(l):
count2 += 1
print(count2)