Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Write a class that, when given a string, will return an uppercase string with each letter shifted forward in the
- # alphabet by however many spots the cipher was initialized to.
- from string import ascii_uppercase
- class CaesarCipher(object):
- def __init__(self, shift):
- self.shift = shift
- def encode(self, str_):
- self.str_ = str_
- result = ''
- for i in range(len(str_)):
- if str_[i].upper() in ascii_uppercase:
- try:
- result += ascii_uppercase[ascii_uppercase.index(str_[i].upper()) + self.shift]
- except IndexError:
- result += ascii_uppercase[(ascii_uppercase.index(str_[i].upper()) \
- + self.shift) - len(ascii_uppercase)]
- else:
- result += str_[i]
- return result
- def decode(self, str_):
- self.str_ = str_
- result = ''
- for i in range(len(str_)):
- if str_[i].upper() in ascii_uppercase:
- try:
- result += ascii_uppercase[ascii_uppercase.index(str_[i].upper()) - self.shift]
- except IndexError:
- result += ascii_uppercase[len(ascii_uppercase) \
- - (ascii_uppercase.index(str_[i].upper()) + self.shift)]
- else:
- result += str_[i]
- return result
- c = CaesarCipher(5)
- print(c.encode("CodeWars"))
- print(c.decode('HTIJBFWX'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement