forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsol1.py
70 lines (50 loc) · 2.12 KB
/
sol1.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
"""
Project Euler Problem 79: https://projecteuler.net/problem=79
Passcode derivation
A common security method used for online banking is to ask the user for three
random characters from a passcode. For example, if the passcode was 531278,
they may ask for the 2nd, 3rd, and 5th characters; the expected reply would
be: 317.
The text file, keylog.txt, contains fifty successful login attempts.
Given that the three characters are always asked for in order, analyse the file
so as to determine the shortest possible secret passcode of unknown length.
"""
importitertools
frompathlibimportPath
deffind_secret_passcode(logins: list[str]) ->int:
"""
Returns the shortest possible secret passcode of unknown length.
>>> find_secret_passcode(["135", "259", "235", "189", "690", "168", "120",
... "136", "289", "589", "160", "165", "580", "369", "250", "280"])
12365890
>>> find_secret_passcode(["426", "281", "061", "819" "268", "406", "420",
... "428", "209", "689", "019", "421", "469", "261", "681", "201"])
4206819
"""
# Split each login by character e.g. '319' -> ('3', '1', '9')
split_logins= [tuple(login) forlogininlogins]
unique_chars= {charforlogininsplit_loginsforcharinlogin}
forpermutationinitertools.permutations(unique_chars):
satisfied=True
forlogininlogins:
ifnot (
permutation.index(login[0])
<permutation.index(login[1])
<permutation.index(login[2])
):
satisfied=False
break
ifsatisfied:
returnint("".join(permutation))
raiseException("Unable to find the secret passcode")
defsolution(input_file: str="keylog.txt") ->int:
"""
Returns the shortest possible secret passcode of unknown length
for successful login attempts given by `input_file` text file.
>>> solution("keylog_test.txt")
6312980
"""
logins=Path(__file__).parent.joinpath(input_file).read_text().splitlines()
returnfind_secret_passcode(logins)
if__name__=="__main__":
print(f"{solution() =}")