-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesar.py
57 lines (40 loc) · 1.59 KB
/
caesar.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def encrypt(text,rot):
"""Your function should return the result of rotating each letter in the text by rot places to the right"""
#list = text.split()
newtext = ""
for word in text:
for letter in range(len(word)):
if word[letter].isalpha() == True:
newletter = rotate_character(word[letter],rot)
newtext = newtext + newletter
else:
newtext = newtext + word[letter]
return newtext
def alphabet_position(letter):
import string
"""receives a letter (a string with only one alphabetic character)
and returns the 0-based numerical position of that letter within the alphabet. It should be case-insensitive."""
if ord(letter) < 97:
pos = string.ascii_uppercase.index(letter)
elif ord(letter) >= 97:
pos = string.ascii_lowercase.index(letter)
return pos
def rotate_character(char,rot):
import string
"""receives a character char (a string of length 1), and an integer rot.
Your function should return a new string of length 1, the result of rotating char by rot number of places to the right."""
value = ord(char)
#rotate = rot % 26
if 65 <= value <= 90:
newcharpos = alphabet_position(char)
newcharpos += rot
newcharpos = newcharpos % 26
newchar = string.ascii_uppercase[newcharpos]
elif 97 <= value <= 122:
newcharpos = alphabet_position(char)
newcharpos += rot
newcharpos = newcharpos % 26
newchar = string.ascii_lowercase[newcharpos]
else:
return char
return newchar