Skip to content

Commit 59b8869

Browse files
Resolved #12306
Done for Hacktoberfest 2024
1 parent 6e24935 commit 59b8869

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

ciphers/rot13.py

+15-12
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
def dencrypt(s: str, n: int = 13) -> str:
1+
def dencrypt(s: str) -> str:
22
"""
3+
Performs ROT13 encryption/decryption on the input string `s`.
4+
35
https://en.wikipedia.org/wiki/ROT13
46
57
>>> msg = "My secret bank account number is 173-52946 so don't tell anyone!!"
@@ -9,29 +11,30 @@ def dencrypt(s: str, n: int = 13) -> str:
911
>>> dencrypt(s) == msg
1012
True
1113
"""
12-
out = ""
14+
# Validate input
15+
assert isinstance(s, str), "Input must be a string"
16+
17+
# Using list to accumulate characters for efficiency
18+
out = []
1319
for c in s:
1420
if "A" <= c <= "Z":
15-
out += chr(ord("A") + (ord(c) - ord("A") + n) % 26)
21+
out.append(chr(ord("A") + (ord(c) - ord("A") + 13) % 26))
1622
elif "a" <= c <= "z":
17-
out += chr(ord("a") + (ord(c) - ord("a") + n) % 26)
23+
out.append(chr(ord("a") + (ord(c) - ord("a") + 13) % 26))
1824
else:
19-
out += c
20-
return out
21-
25+
out.append(c)
26+
return "".join(out)
2227

2328
def main() -> None:
2429
s0 = input("Enter message: ")
2530

26-
s1 = dencrypt(s0, 13)
31+
s1 = dencrypt(s0)
2732
print("Encryption:", s1)
2833

29-
s2 = dencrypt(s1, 13)
30-
print("Decryption: ", s2)
31-
34+
s2 = dencrypt(s1)
35+
print("Decryption:", s2)
3236

3337
if __name__ == "__main__":
3438
import doctest
35-
3639
doctest.testmod()
3740
main()

0 commit comments

Comments
 (0)