From 67a5bb9695cf98890056d68f3974bb3e30cd6b9f Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sun, 8 Dec 2019 20:13:49 +0100 Subject: [PATCH] 2019: d04: ex2: add solution --- 2019/d04/ex2/ex2.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100755 2019/d04/ex2/ex2.py diff --git a/2019/d04/ex2/ex2.py b/2019/d04/ex2/ex2.py new file mode 100755 index 0000000..883abf9 --- /dev/null +++ b/2019/d04/ex2/ex2.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python + +from typing import Iterator + + +def is_valid_password(p: int) -> bool: + digits = str(p) + + def has_unique_adjacent_digit(): + counts = {d: 0 for d in range(10)} + for (a, b) in zip(digits, digits[1:]): + if a == b: + counts[int(a)] += 1 + return any(count == 1 for count in counts.values()) + + def digits_never_decrease(): + return all(a == b for a, b in zip(sorted(digits), digits)) + + return has_unique_adjacent_digit() and digits_never_decrease() + + +def compute_pass(begin: int, end: int) -> Iterator[int]: + for p in range(begin, end + 1): + if is_valid_password(p): + yield p + + +def main() -> None: + begin = 264793 + end = 803935 + print(sum(1 for p in compute_pass(begin, end))) + + +if __name__ == "__main__": + main()