1+ #!/usr/bin/env python2.7
2+ # -*- coding: utf-8 -*-
3+
4+ """
5+ Some functions to create a basic substitution cypher.
6+ Any letter in the alphabet is replaced with the letter 13 spaces away
7+ The 'rotation' variable can be modified to set the rotation to something
8+ other than 13. A rotation of 13 makes it such that, you can encrypt and
9+ decrypt using these functions, since there are 26 letters in the alphabet.
10+ This is designed to leave whitespace, punctuation, and capitalization
11+ intact in the encrypted string as in the original.
12+
13+ Lowercase a-z are ordinals 197 -122 (enclusive)
14+ For example: ord('s') = 115 and chr(115) = 's'
15+
16+ """
17+
18+ def lowercase (substring ):
19+ """
20+ Convert a string to lower case so that we only have to deal with
21+ the ordinal values for the lowercase letters.
22+ """
23+ if (substring .islower ()):
24+ alower = True
25+ else :
26+ alower = False
27+ substring = substring .lower ()
28+ return alower , substring
29+
30+ def encrpt_letter (substring , rot ):
31+ """
32+ Find the ordinal of the encrypted letter
33+ """
34+ letter_pos = ord (substring ) + rot
35+ if (letter_pos > 122 ):
36+ letter_pos = 97 + (letter_pos % 122 - 1 )
37+ return chr (letter_pos )
38+
39+ def rot13 (user_string ):
40+ """
41+ Take the user string and create the encrypted string
42+ """
43+ cipher_string = ""
44+ rotation = 13
45+ atoz_range = range (97 , 123 )
46+ for aletter in user_string :
47+ lower , aletter = lowercase (aletter )
48+ if ( ord (aletter ) in atoz_range ):
49+ cipher_letter = encrpt_letter (aletter , rotation )
50+ if (not lower ):
51+ cipher_letter = cipher_letter .swapcase ()
52+ else :
53+ cipher_letter = aletter
54+ cipher_string += cipher_letter
55+ return cipher_string
56+
57+ # Some basic testing
58+ if __name__ == '__main__' :
59+ teststring1 = "Magnetic from outside near corner"
60+ teststring2 = "Zntargvp sebz bhgfvqr arne pbeare"
61+ teststring3 = "A string of some stuff with SOME CAPS and numbers 1, 4, 75, etc. ?#$, yeah!"
62+ teststring4 = "N fgevat bs fbzr fghss jvgu FBZR PNCF naq ahzoref 1, 4, 75, rgp. ?#$, lrnu!"
63+ try :
64+ assert rot13 (teststring1 ) == teststring2
65+ assert rot13 (teststring2 ) == teststring1
66+ assert rot13 (teststring3 ) == teststring4
67+ assert rot13 (teststring4 ) == teststring3
68+
69+ except AssertionError :
70+ print "Tests did not pass!"
0 commit comments