Advertisement
Guest User

Untitled

a guest
Oct 26th, 2015
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. ## Write a class that, when given a string, will return an uppercase string with each letter shifted forward in the
  2. # alphabet by however many spots the cipher was initialized to.
  3. from string import ascii_uppercase
  4. class CaesarCipher(object):
  5.  
  6.     def __init__(self, shift):
  7.         self.shift = shift
  8.  
  9.     def encode(self, str_):
  10.         self.str_ = str_
  11.         result = ''
  12.         for i in range(len(str_)):
  13.             if str_[i].upper() in ascii_uppercase:
  14.                 try:
  15.                     result += ascii_uppercase[ascii_uppercase.index(str_[i].upper()) + self.shift]
  16.                 except IndexError:
  17.                     result += ascii_uppercase[(ascii_uppercase.index(str_[i].upper()) \
  18.                                                + self.shift) - len(ascii_uppercase)]
  19.             else:
  20.                 result += str_[i]
  21.         return result
  22.  
  23.  
  24.     def decode(self, str_):
  25.         self.str_ = str_
  26.         result = ''
  27.         for i in range(len(str_)):
  28.             if str_[i].upper() in ascii_uppercase:
  29.                 try:
  30.                     result += ascii_uppercase[ascii_uppercase.index(str_[i].upper()) - self.shift]
  31.                 except IndexError:
  32.                     result += ascii_uppercase[len(ascii_uppercase) \
  33.                                               - (ascii_uppercase.index(str_[i].upper()) + self.shift)]
  34.             else:
  35.                 result += str_[i]
  36.         return result
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43. c = CaesarCipher(5)
  44. print(c.encode("CodeWars"))
  45. print(c.decode('HTIJBFWX'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement