|
2 | 2 |
|
3 | 3 | import re |
4 | 4 |
|
| 5 | + |
5 | 6 | def check_policy(policy: str, password: str, mode: int = 1) -> bool: |
6 | 7 | numbers, char = policy.split(" ") |
7 | 8 | lower_bound, upper_bound = [int(num) for num in numbers.split("-")] |
8 | 9 |
|
9 | 10 | if mode == 1: |
10 | 11 | occ = password.count(char) |
11 | | - return lower_bound <= occ <= upper_bound |
| 12 | + return lower_bound <= occ <= upper_bound |
12 | 13 | else: |
13 | 14 | # policy starts at place 1, not 0 in the string |
14 | | - matches = [match.start()+1 for match in re.finditer(char, password)] |
| 15 | + matches = [match.start() + 1 for match in re.finditer(char, password)] |
15 | 16 | return bool((lower_bound in matches) ^ (upper_bound in matches)) |
16 | 17 |
|
17 | | - |
18 | | - |
19 | 18 |
|
20 | 19 | if __name__ == "__main__": |
21 | 20 | with open("input", "r") as infile: |
22 | 21 | check_lines = [line.strip().split(":") for line in infile] |
23 | | - print("Valid passwords for part1:", sum([check_policy(policy.strip(), password.strip()) for policy, password in check_lines])) |
24 | | - print("Valid passwords for part2:", sum([check_policy(policy.strip(), password.strip(), 2) for policy, password in check_lines])) |
| 22 | + print( |
| 23 | + "Valid passwords for part1:", |
| 24 | + sum( |
| 25 | + [ |
| 26 | + check_policy(policy.strip(), password.strip()) |
| 27 | + for policy, password in check_lines |
| 28 | + ] |
| 29 | + ), |
| 30 | + ) |
| 31 | + print( |
| 32 | + "Valid passwords for part2:", |
| 33 | + sum( |
| 34 | + [ |
| 35 | + check_policy(policy.strip(), password.strip(), 2) |
| 36 | + for policy, password in check_lines |
| 37 | + ] |
| 38 | + ), |
| 39 | + ) |
0 commit comments