I'm trying to write a function rot(c,n)
that rotates a single character c forward by n spots in the alphabet.
def rot(c,n):
""" rotate c forward by n characters,
wrapping as needed; only letters change
"""
if 'a' <= c <= 'z': # lower-case
new_ord = ord(c) + n
if new_ord > ord('z'):
new_ord = new_ord - (2*n)
elif 'A' <= c <= 'Z': # upper-case
new_ord = ord(c) + n
if new_ord > ord('Z'):
new_ord = new_ord - (2*n)
else: # non-alpha
new_ord = ord(c)
return chr(new_ord)
However my desired outputs are as follow:
>>> rot('a', 2)
'c'
>>> rot('y', 2)
'a'
>>> rot('A', 3)
'D'
>>> rot('Y', 3)
'B'
>>> rot('!', 4)
'!'
I keep getting the wrong outputs. Can someone tell me what I'm doing wrong?
Your problem is here:
new_ord = new_ord - (2*n)
The idea is that when you go past z, you have to remove exactly the whole alphabet and not remove twice what you just added.
Try:
new_ord = new_ord - 26