-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathatbash_cipher.py
More file actions
42 lines (33 loc) · 1021 Bytes
/
atbash_cipher.py
File metadata and controls
42 lines (33 loc) · 1021 Bytes
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
"""
Atbash Cipher
Atbash cipher maps each letter of the alphabet to its reverse.
The first letter 'a' maps to 'z', 'b' maps to 'y', and so on.
Reference: https://en.wikipedia.org/wiki/Atbash
Complexity:
Time: O(n) where n is the length of the input string
Space: O(n)
"""
from __future__ import annotations
def atbash(text: str) -> str:
"""Encrypt or decrypt a string using the Atbash cipher.
Args:
text: The input string to transform.
Returns:
The Atbash-transformed string.
Examples:
>>> atbash("abcdefghijklmno")
'zyxwvutsrqponml'
"""
translated = ""
for char in text:
code = ord(char)
if char.isalpha():
if char.isupper():
offset = code - ord("A")
translated += chr(ord("Z") - offset)
elif char.islower():
offset = code - ord("a")
translated += chr(ord("z") - offset)
else:
translated += char
return translated