-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_password_list.py
78 lines (58 loc) · 2 KB
/
check_password_list.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
"""
Advent of Code 2020 - Day 2: Password Philosophy
"""
import argparse
import os
import sys
from collections import Counter
from pathlib import Path
from typing import List
def filter_valid_passwords(file: Path) -> List[str]:
"""
Return only valid passwords from the ones listed in a file
:param file: password list file
:return: password meeting requirements
"""
for line in open(file):
min_max, char, password = line.strip().split(' ')
min, max = [int(part) for part in min_max.split('-')]
char = char[0]
cnt = Counter(c for c in password)
if min <= cnt[char] <= max:
yield password
def filter_valid_passwords_part2(file: Path) -> List[str]:
"""
Filter function for part 2 of the challenge
:param file: password list file
:return: password meeting requirements
"""
for line in open(file):
min_max, char, password = line.strip().split(' ')
first_index, second_index = [int(part) - 1
for part in min_max.split('-')]
char = char[0]
if (password[first_index] == char) ^ (password[second_index] == char):
yield password
def main() -> int:
"""
Main function
:return: Shell exit code
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('password_file', type=str,
help='Password file to inspect')
args = parser.parse_args()
password_file = Path(args.password_file)
if not os.path.isfile(password_file):
raise FileNotFoundError(f'File {password_file} does not exists')
valid_passwords = filter_valid_passwords(file=password_file)
print(f'Found {len(list(valid_passwords))} passwords')
valid_passwords = filter_valid_passwords_part2(file=password_file)
print(f'Found {len(list(valid_passwords))} passwords for part 2')
return 0
if __name__ == '__main__':
"""
Command line entry-point
"""
sys.exit(main())