From 4f8c876f2d5a8b416c95e1156af60bf43d1fdfd6 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Wed, 2 Dec 2020 11:20:12 +0100 Subject: [PATCH] 2020: d02: ex1: add solution --- 2020/d02/ex1/ex1.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100755 2020/d02/ex1/ex1.py diff --git a/2020/d02/ex1/ex1.py b/2020/d02/ex1/ex1.py new file mode 100755 index 0000000..fca2919 --- /dev/null +++ b/2020/d02/ex1/ex1.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python + +import re +import sys +from dataclasses import dataclass +from typing import List + + +@dataclass +class Policy: + min: int + max: int + letter: str + + +@dataclass +class Password: + policy: Policy + password: str + + +def is_valid(pwd: Password) -> bool: + occurences = pwd.password.count(pwd.policy.letter) + return pwd.policy.min <= occurences <= pwd.policy.max + + +def solve(passwords: List[Password]) -> int: + return sum(map(is_valid, passwords)) + + +def main() -> None: + pattern = re.compile("([0-9]+)-([0-9]+) (.): (.+)") + input = [ + Password(Policy(int(m.group(1)), int(m.group(2)), m.group(3)), m.group(4)) + for m in (pattern.match(line) for line in sys.stdin.readlines()) + if m + ] + print(solve(input)) + + +if __name__ == "__main__": + main()