Skip to content

Update atbash cipher (doc, doctest, performance) #2017

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 20, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 55 additions & 4 deletions ciphers/atbash.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,66 @@
def atbash():
""" https://en.wikipedia.org/wiki/Atbash """
import string


def atbash_slow(sequence: str) -> str:
"""
>>> atbash_slow("ABCDEFG")
'ZYXWVUT'

>>> atbash_slow("aW;;123BX")
'zD;;123YC'
"""
output = ""
for i in input("Enter the sentence to be encrypted ").strip():
for i in sequence:
extract = ord(i)
if 65 <= extract <= 90:
output += chr(155 - extract)
elif 97 <= extract <= 122:
output += chr(219 - extract)
else:
output += i
print(output)
return output


def atbash(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)] if c in letters else c for c in sequence
)


def benchmark() -> None:
"""Let's benchmark them side-by-side..."""
from timeit import timeit

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__":
atbash()
for sequence in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
print(f"{sequence} encrypted in atbash: {atbash(sequence)}")
benchmark()