From 9128f6bdc40d204325a30cff86429356ef2fc5da Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sun, 3 Jan 2021 20:03:45 -0500 Subject: [PATCH] A terrible idea oh no --- aoc2020/day02/solution.py | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 aoc2020/day02/solution.py diff --git a/aoc2020/day02/solution.py b/aoc2020/day02/solution.py new file mode 100644 index 0000000..69a2193 --- /dev/null +++ b/aoc2020/day02/solution.py @@ -0,0 +1,50 @@ +import sys + + +def main() -> int: + n_valid = 0 + total = 0 + + for pol_pas in [PolicyPassword.fromstring(s) for s in sys.stdin.readlines(False)]: + if pol_pas.is_valid(): + n_valid += 1 + total += 1 + + print(f"{n_valid}/{total} valid") + + return 0 + + +class Policy: + def __init__(self, char: str, min_count: int, max_count: int): + self.char = char + self.min_count = min_count + self.max_count = max_count + + @classmethod + def fromstring(cls, input_string) -> "Policy": + parts = [s.strip() for s in input_string.split(" ")][:2] + min_max = [int(s) for s in parts[0].split("-")][:2] + return cls(parts[1], min_max[0], min_max[1]) + + def is_valid(self, password: str) -> bool: + actual = password.count(self.char) + return actual >= self.min_count and actual <= self.max_count + + +class PolicyPassword: + def __init__(self, policy: "Policy", password: str): + self.policy = policy + self.password = password + + @classmethod + def fromstring(cls, input_string: str) -> "PolicyPassword": + parts = [s.strip() for s in input_string.split(":")][:2] + return cls(Policy.fromstring(parts[0]), parts[1]) + + def is_valid(self) -> bool: + return self.policy.is_valid(self.password) + + +if __name__ == "__main__": + sys.exit(main())