Teaching Kids Programming – ROT13 String Cipher Algorithm in Python


Teaching Kids Programming: Videos on Data Structures and Algorithms

ROT13 Cipher transform a text to a disguised version that only uppercase and lowercase characters are rotated 13 positions:

i.e. The letters:
ABCDEFGHIJKLM transformed to
NOPQRSTUVWXYZ
and
abcdefghijklm transformed to
nopqrstuvwxyz

For example, rot13(“Hello, World!!”)=”Uryyb, Jbeyq!!”

We can iterate each character and if it is a uppercase (isupper) or a lowercase (islower), we then compute the ASCII code of the character, add 13 (rotated 13 positions) and round up to begining if applicable by %13, then convert it back to character using chr() function.

Other characters, we simply append it without any transformation to the list. Then finally, we apply the join to concatenate all the characters in the list.

1
2
3
4
5
6
7
8
9
10
def rot13(s):
    a = []
    for i in s:
        if i.isupper():
            a.append(chr(65 + (ord(i) - 65 + 13) % 26))
        elif i.islower():
            a.append(chr(97 + (ord(i) - 97 + 13) % 26))
        else:
            a.append(i)
    return "".join(a)
def rot13(s):
    a = []
    for i in s:
        if i.isupper():
            a.append(chr(65 + (ord(i) - 65 + 13) % 26))
        elif i.islower():
            a.append(chr(97 + (ord(i) - 97 + 13) % 26))
        else:
            a.append(i)
    return "".join(a)

We can look for the characters in the alphabeta string using find function.

1
2
3
4
5
6
7
8
9
10
11
12
def rot13(s):
    ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    abc = "abcdefghijklmnopqrstuvwxyz"
    a = []
    for i in s:
        if i.isupper():
            a.append(ABC[(ABC.find(i) + 13) % 26])
        elif i.islower():
            a.append(abc[(abc.find(i) + 13) % 26])
        else:
            a.append(i)
    return "".join(a)
def rot13(s):
    ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    abc = "abcdefghijklmnopqrstuvwxyz"
    a = []
    for i in s:
        if i.isupper():
            a.append(ABC[(ABC.find(i) + 13) % 26])
        elif i.islower():
            a.append(abc[(abc.find(i) + 13) % 26])
        else:
            a.append(i)
    return "".join(a)

Time complexity is O(N) and space complexity is O(1). The ROT13 Cipher is like XOR – which you perform the twice it will give you the original input string i.e. tex_49fdc4af7131cf39220d80ebddfcde14 Teaching Kids Programming - ROT13 String Cipher Algorithm in Python algorithms python string teaching kids programming youtube video

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
398 words
Last Post: C Function to Run External Command and Capture the Output
Next Post: C Macro/Function to Convert a IP Address into a 32-bit Integer

The Permanent URL is: Teaching Kids Programming – ROT13 String Cipher Algorithm in Python

Leave a Reply