forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatbash.py
More file actions
Latest commit
66 lines (55 loc) · 1.56 KB
/
Copy pathatbash.py
File metadata and controls
66 lines (55 loc) · 1.56 KB
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
""" https://en.wikipedia.org/wiki/Atbash """
importstring
defatbash_slow(sequence: str) ->str:
"""
>>> atbash_slow("ABCDEFG")
'ZYXWVUT'
>>> atbash_slow("aW;;123BX")
'zD;;123YC'
"""
output=""
foriinsequence:
extract=ord(i)
if65<=extract<=90:
output+=chr(155-extract)
elif97<=extract<=122:
output+=chr(219-extract)
else:
output+=i
returnoutput
defatbash(sequence: str) ->str:
"""
>>> atbash("ABCDEFG")
'ZYXWVUT'
>>> atbash("aW;;123BX")
'zD;;123YC'
"""
letters=string.ascii_letters
letters_reversed=string.ascii_lowercase[::-1] +string.ascii_uppercase[::-1]
return"".join(
letters_reversed[letters.index(c)] ifcinletterselsecforcinsequence
)
defbenchmark() ->None:
"""Let's benchmark them side-by-side..."""
fromtimeitimporttimeit
print("Running performance benchmarks...")
print(
"> atbash_slow()",
timeit(
"atbash_slow(printable)",
setup="from string import printable ; from __main__ import atbash_slow",
),
"seconds",
)
print(
"> atbash()",
timeit(
"atbash(printable)",
setup="from string import printable ; from __main__ import atbash",
),
"seconds",
)
if__name__=="__main__":
forexamplein ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
print(f"{example} encrypted in atbash: {atbash(example)}")
benchmark()