mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
bc8df6de31
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.2.2 → v0.3.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.2.2...v0.3.2) - [github.com/pre-commit/mirrors-mypy: v1.8.0 → v1.9.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.8.0...v1.9.0) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
55 lines
1.4 KiB
Python
55 lines
1.4 KiB
Python
"""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 sequence:
|
|
extract = ord(i)
|
|
if 65 <= extract <= 90:
|
|
output += chr(155 - extract)
|
|
elif 97 <= extract <= 122:
|
|
output += chr(219 - extract)
|
|
else:
|
|
output += i
|
|
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 our functions side-by-side..."""
|
|
from timeit import timeit
|
|
|
|
print("Running performance benchmarks...")
|
|
setup = "from string import printable ; from __main__ import atbash, atbash_slow"
|
|
print(f"> atbash_slow(): {timeit('atbash_slow(printable)', setup=setup)} seconds")
|
|
print(f"> atbash(): {timeit('atbash(printable)', setup=setup)} seconds")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
|
|
print(f"{example} encrypted in atbash: {atbash(example)}")
|
|
benchmark()
|