From 7cf0dcfe320707e8b8192a6f1c675ac69681b72d Mon Sep 17 00:00:00 2001 From: Fedor Lyanguzov Date: Mon, 3 May 2021 19:31:28 +0300 Subject: [PATCH] Solve 4.2 --- 01/01.py | 2 +- 02/02.py | 2 +- 03/03.py | 2 +- 04/04.py | 50 +++++++++++++++++++++++++++++++++++++++++++++++--- 4 files changed, 50 insertions(+), 6 deletions(-) diff --git a/01/01.py b/01/01.py index 1491de2..84f5fc0 100644 --- a/01/01.py +++ b/01/01.py @@ -1,6 +1,6 @@ from itertools import combinations -with open('01-input') as f: +with open('input') as f: numbers = {int(row.strip()) for row in f} for n in numbers: diff --git a/02/02.py b/02/02.py index 77417a2..d898223 100644 --- a/02/02.py +++ b/02/02.py @@ -1,6 +1,6 @@ import re -with open('02-input') as f: +with open('input') as f: passwords = [row.strip() for row in f] pattern = re.compile(r'(\d*)-(\d*) (\w): (.*)') diff --git a/03/03.py b/03/03.py index 8aca1d7..1fa05ac 100644 --- a/03/03.py +++ b/03/03.py @@ -1,6 +1,6 @@ import re -with open('03-input') as f: +with open('input') as f: landscape = [row.strip() for row in f] count = 0 diff --git a/04/04.py b/04/04.py index bccfd90..95efde7 100644 --- a/04/04.py +++ b/04/04.py @@ -1,6 +1,6 @@ import re -with open('04-input') as f: +with open('input') as f: text = f.read() while '\n\n\n' in text: @@ -12,12 +12,56 @@ print(sum(1 for p in passports if valid.issubset(p.keys()))) from functools import partial def int_val(least, most, n): - return least<=n<=most + return least<=int(n)<=most v_byr = partial(int_val, 1920, 2002) v_iyr = partial(int_val, 2010, 2020) v_eyr = partial(int_val, 2020, 2030) v_cm = partial(int_val, 150, 193) v_in = partial(int_val, 59, 76) +class NotValid(Exception): + pass + +def has_correct_keys(passport): + if not valid.issubset(passport.keys()): + raise NotValid("keys") +def valid_field(key, func, passport): + if not func(passport[key]): + raise NotValid(key) +def valid_ecl(passport): + if passport["ecl"] not in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth",]: + raise NotValid("ecl") +def valid_pid(passport): + if not re.match(r"^\d{9}$", passport["pid"]): + raise NotValid("pid") +def valid_hcl(passport): + if not re.match(r"^\#[0-9a-f]{6}$", passport["hcl"]): + raise NotValid("hcl") +def valid_hgt(passport): + if not (m := re.match(r"^(\d+)(cm|in)$", passport["hgt"])): + raise NotValid + if m.group(2)=="in": + if not v_in(m.group(1)): + raise NotValid + else: + if not v_cm(m.group(1)): + raise NotValid + +checks = [has_correct_keys, + partial(valid_field, "byr", v_byr), + partial(valid_field, "iyr", v_iyr), + partial(valid_field, "eyr", v_eyr), + valid_ecl, + valid_pid, + valid_hcl, + valid_hgt, + ] def is_valid(passport): - valid.issubset(p.keys()) + try: + for check in checks: + check(passport) + return True + except NotValid as e: + return False + +print(len(list(filter(is_valid, passports))))