In this ProgrammingPraxis challenge we have to build a simple Caesar Cipher with a special property, called rot13 :

ROT13 (“rotate by 13 places“, sometimes hyphenated ROT-13) is a simple substitution cipher used in online forums as a means of hiding spoilers, punchlines, puzzle solutions, and offensive materials from the casual glance. ROT13 has been described as the “Usenet equivalent of a magazine printing the answer to a quiz upside down”.ROT13 is an example of the Caesar cipher, developed in ancient Rome. (Wikipedia)

Applying ROT13 to a piece of text merely requires examining its alphabetic characters and replacing each one by the letter 13 places further along in the alphabet, wrapping back to the beginning if necessary. A becomes NB becomes O, and so on up to M, which becomes Z, then the sequence continues at the beginning of the alphabet: N becomes AO becomes B, and so on to Z, which becomes M. Only those letters which occur in the English alphabet are affected; numbers, symbols, whitespace, and all other characters are left unchanged. Because there are 26 letters in the English alphabet and 26 = 2 × 13, the ROT13 function is its own inverse. (Wikipedia)

Write a function that takes a string and returns the ROT13 version of the string; you may assume that the character set is ascii. What is the meaning of “Cebtenzzvat Cenkvf vf sha!” .

The transition table for rot13:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
N O P Q R S T U V W X Y Z A B C D E F G H I J K L M



Examples of transitions:

The Wall
Gur Jnyy
Smoke on the water Fzbxr ba gur jngre



Initially I wanted to resolve the challenge in a functional programming language. Given the fact that my Haskell skills are very low, I’ve tried to write a functional approach in python . The results… lesser readability, fewer lines of code & fewer minutes:

from string import letters, lowercase, uppercase

numlet=26
num=13
llist = lambda let : [[let[x], let[(x + num) % numlet]] for x in range(numlet)]
shifted = dict(llist(uppercase) + llist(lowercase))

def get_shifted(text):
    return "".join([shifted[s] if s in letters else s for s in text])
if __name__ == '__main__':
    print get_shifted("Cebtenzzvat Cenkvf vf sha!")

And the output:

Programming Praxis is fun!

Leave a reply

required


2 × = sixteen

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>