Skip to content

Commit c4d25e9

Browse files
[Sync Iteration] python/rotational-cipher/2
1 parent 195e7bb commit c4d25e9

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
The rotational cipher, also sometimes called the Caesar cipher.
3+
4+
The Caesar cipher is a simple shift cipher that relies on transposing
5+
all the letters in the alphabet using an integer key between 0 and 26.
6+
Using a key of 0 or 26 will always yield the same output due to modular
7+
arithmetic. The letter is shifted for as many values as the value of the key.
8+
"""
9+
10+
import string
11+
12+
LETTERS_LOWER: str = string.ascii_lowercase
13+
LETTERS_UPPER: str = string.ascii_uppercase
14+
15+
16+
def rotate(text: str, key: int) -> str:
17+
"""
18+
Rotate each letter in the text by the specified key using Caesar cipher.
19+
20+
Non-alphabetic characters remain unchanged. The rotation wraps around
21+
the alphabet (a->z, A->Z) using modular arithmetic.
22+
23+
:param text: The input string to be rotated
24+
:param key: The number of positions to shift each letter (0-25)
25+
:return: The rotated string with letters shifted by key positions
26+
27+
Examples:
28+
>>> rotate("abc", 1)
29+
"bcd"
30+
>>> rotate("Hello, World!", 13)
31+
"Uryyb, Jbeyq!"
32+
"""
33+
new_str: list[str] = []
34+
for char in text:
35+
# Lower case
36+
if char in LETTERS_LOWER:
37+
new_str.append(
38+
LETTERS_LOWER[(LETTERS_LOWER.index(char) + key) % 26]
39+
)
40+
# Upper case
41+
elif char in LETTERS_UPPER:
42+
new_str.append(
43+
LETTERS_UPPER[(LETTERS_UPPER.index(char) + key) % 26]
44+
)
45+
# Not a letter
46+
else:
47+
new_str.append(char)
48+
# Convert to a string
49+
return "".join(new_str)

0 commit comments

Comments
 (0)