Skip to content

Commit 06cb5d3

Browse files
authored
Update atbash.py
1 parent 208adb1 commit 06cb5d3

1 file changed

Lines changed: 31 additions & 45 deletions

File tree

ciphers/atbash.py

Lines changed: 31 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -2,53 +2,39 @@
22

33
import string
44

5-
6-
def atbash_slow(sequence: str) -> str:
7-
"""
8-
>>> atbash_slow("ABCDEFG")
9-
'ZYXWVUT'
10-
11-
>>> atbash_slow("aW;;123BX")
12-
'zD;;123YC'
13-
"""
14-
output = ""
15-
for i in sequence:
16-
extract = ord(i)
17-
if 65 <= extract <= 90:
18-
output += chr(155 - extract)
19-
elif 97 <= extract <= 122:
20-
output += chr(219 - extract)
21-
else:
22-
output += i
23-
return output
24-
25-
26-
def atbash(sequence: str) -> str:
5+
def atbash(text: str) -> str:
276
"""
28-
>>> atbash("ABCDEFG")
29-
'ZYXWVUT'
30-
31-
>>> atbash("aW;;123BX")
32-
'zD;;123YC'
7+
Encodes or decodes text using the Atbash cipher.
8+
9+
The Atbash cipher substitutes each letter with its mirror in the alphabet:
10+
A -> Z, B -> Y, C -> X, ... Z -> A (case is preserved)
11+
Non-alphabetic characters are left unchanged.
12+
13+
Args:
14+
text: The input string to encode/decode
15+
16+
Returns:
17+
The transformed string
3318
"""
34-
letters = string.ascii_letters
35-
letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
36-
return "".join(
37-
letters_reversed[letters.index(c)] if c in letters else c for c in sequence
19+
# Create translation tables for uppercase and lowercase
20+
lowercase_map = str.maketrans(
21+
string.ascii_lowercase,
22+
string.ascii_lowercase[::-1]
3823
)
24+
uppercase_map = str.maketrans(
25+
string.ascii_uppercase,
26+
string.ascii_uppercase[::-1]
27+
)
28+
29+
# Apply both translation mappings
30+
return text.translate(lowercase_map).translate(uppercase_map)
3931

40-
41-
def benchmark() -> None:
42-
"""Let's benchmark our functions side-by-side..."""
43-
from timeit import timeit
44-
45-
print("Running performance benchmarks...")
46-
setup = "from string import printable ; from __main__ import atbash, atbash_slow"
47-
print(f"> atbash_slow(): {timeit('atbash_slow(printable)', setup=setup)} seconds")
48-
print(f"> atbash(): {timeit('atbash(printable)', setup=setup)} seconds")
49-
50-
32+
# Example usage
5133
if __name__ == "__main__":
52-
for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
53-
print(f"{example} encrypted in atbash: {atbash(example)}")
54-
benchmark()
34+
test_string = "Hello, World! 123"
35+
encoded = atbash(test_string)
36+
decoded = atbash(encoded)
37+
38+
print(f"Original: {test_string}")
39+
print(f"Encoded: {encoded}")
40+
print(f"Decoded: {decoded}")

0 commit comments

Comments
 (0)