Skip to content

Commit 965d02a

Browse files
l3str4ngecclauss
andauthored
Update atbash cipher (doc, doctest, performance) (TheAlgorithms#2017)
* Update atbash * Add benchmark() to quantify the performance improvement Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 777ddca commit 965d02a

File tree

1 file changed

+55
-4
lines changed

1 file changed

+55
-4
lines changed

ciphers/atbash.py

+55-4
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,66 @@
1-
def atbash():
1+
""" https://en.wikipedia.org/wiki/Atbash """
2+
import string
3+
4+
5+
def atbash_slow(sequence: str) -> str:
6+
"""
7+
>>> atbash_slow("ABCDEFG")
8+
'ZYXWVUT'
9+
10+
>>> atbash_slow("aW;;123BX")
11+
'zD;;123YC'
12+
"""
213
output = ""
3-
for i in input("Enter the sentence to be encrypted ").strip():
14+
for i in sequence:
415
extract = ord(i)
516
if 65 <= extract <= 90:
617
output += chr(155 - extract)
718
elif 97 <= extract <= 122:
819
output += chr(219 - extract)
920
else:
1021
output += i
11-
print(output)
22+
return output
23+
24+
25+
def atbash(sequence: str) -> str:
26+
"""
27+
>>> atbash("ABCDEFG")
28+
'ZYXWVUT'
29+
30+
>>> atbash("aW;;123BX")
31+
'zD;;123YC'
32+
"""
33+
letters = string.ascii_letters
34+
letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
35+
return "".join(
36+
letters_reversed[letters.index(c)] if c in letters else c for c in sequence
37+
)
38+
39+
40+
def benchmark() -> None:
41+
"""Let's benchmark them side-by-side..."""
42+
from timeit import timeit
43+
44+
print("Running performance benchmarks...")
45+
print(
46+
"> atbash_slow()",
47+
timeit(
48+
"atbash_slow(printable)",
49+
setup="from string import printable ; from __main__ import atbash_slow",
50+
),
51+
"seconds",
52+
)
53+
print(
54+
"> atbash()",
55+
timeit(
56+
"atbash(printable)",
57+
setup="from string import printable ; from __main__ import atbash",
58+
),
59+
"seconds",
60+
)
1261

1362

1463
if __name__ == "__main__":
15-
atbash()
64+
for sequence in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
65+
print(f"{sequence} encrypted in atbash: {atbash(sequence)}")
66+
benchmark()

0 commit comments

Comments
 (0)