Cool Computer Science Thing of the Day
No Reading Questions
No Quiz
Rot13
- Did you have secret codes to pass messages to friends when you were a kid?
- I did, this is what I used
- Replace each letter with the letter 13 later in the alphabet
Let’s write a function to automate this
def rot13(message): shift = 13 encoded_message = '' for i in range(len(message)): character = message[i] if character in string.ascii_lowercase: character = character + shift encoded_message += character return encoded_message
- This won’t work because character is a string and shift is a number
To fix, convert character to a number, add, convert back to character
def rot13(message): shift = 13 encoded_message = '' for i in range(len(message)): character = message[i] if character in string.ascii_lowercase: index = string.ascii_lowercase.index(character) index = index + shift character += string.ascii_lowercase[index] encoded_message += character return encoded_message
- This will crash for any letters after m in the alphabet because the shifted index will be out of bounds
To solve could use an if statement to shift if it is out of range
def rot13(message): shift = 13 encoded_message = '' for i in range(len(message)): character = message[i] if character in string.ascii_lowercase: index = string.ascii_lowercase.index(character) index = index + shift if index >= len(string.ascii_lowercase): index = index - len(string.ascii_lowercase) character += string.ascii_lowercase[index] encoded_message += character return encoded_message
Another solution is to use mod
def rot13(message): shift = 13 encoded_message = '' for i in range(len(message)): character = message[i] if character in string.ascii_lowercase: index = string.ascii_lowercase.index(character) index = (index + shift) % len(string.ascii_lowercase) character = string.ascii_lowercase[index] encoded_message += character return encoded_message
- This encryption scheme is called rot13, because it rotates 13 characters
- Thirteen because it is half the alphabet, so encoding and decoding are the same function
Using different amounts of shift the encryption scheme is called a Caesar cipher because Julius Caesar used it to encrypt messages to his generals