Skip to content

Commit b135411

Browse files
committed
two solutions in ROT13
CodeWars
1 parent 63cd9b5 commit b135411

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

rot13.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Learn Python together
2+
"""Create a function that takes a string and returns the string ciphered with Rot13.
3+
If there are numbers or special characters included in the string, they should be returned as they are.
4+
Only letters from the latin/english alphabet should be shifted, like in the original Rot13 "implementation".
5+
"""
6+
# Solution 1
7+
def rot13(message):
8+
result = ''
9+
for char in message:
10+
# chek the char is an alphabet
11+
if char.isalpha():
12+
# check the char is uppercase
13+
if char.isupper():
14+
# convert chars to ASCII code, subtract ASCII code of 'A' (65),add rot13 than take modulo 26,
15+
# add ASCII code of 'A' back and convert ASCII code to characters and add it to the result
16+
result += chr((ord(char) - 65 + 13) % 26 + 65)
17+
else:
18+
# convert chars to ASCII code, subtract ASCII code of 'a' (97),add rot13 than take modulo 26,
19+
# add ASCII code of 'a' back and convert ASCII code to characters and add it to the result
20+
result += chr((ord(char) - 97 + 13) % 26 + 97)
21+
else:
22+
# otherwise add char to the result
23+
result += char
24+
return result
25+
26+
# check
27+
print(rot13('test')) # Output -> grfg
28+
print(rot13('Test')) # Output -> Grfg
29+
print(rot13('aA bB zZ 1234 *!?%')) # Output -> nN oO mM 1234 *!?%
30+
31+
# Solution 2 using the encode method
32+
import codecs
33+
def rot13_encode(message):
34+
return codecs.encode(message, 'rot13')
35+
36+
# check
37+
print(rot13_encode('test')) # Output -> grfg
38+
print(rot13_encode('Test')) # Output -> grfg
39+
print(rot13_encode('aA bB zZ 1234 *!?%')) # Output -> nN oO mM 1234 *!?%

0 commit comments

Comments
 (0)