Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. word = "to be or not to be that is the question"
  2. key = [3, 9, 1]
  3.  
  4. def shift(a, k):
  5.     # a is a letter, k is a number
  6.     # ex. shift('b', 2) = 'd'
  7.     #     shift('y', 3) = 'b'
  8.  
  9.     # don't shift non-alphanumeric
  10.     if (not a.isalpha()):
  11.         return a
  12.  
  13.     # shift the letters ascii value (so a is 0, b is 1, ...)
  14.     i = ord(a) - ord('a')
  15.     i += k
  16.     # if we went past 'z', wrap around
  17.     i %= 26
  18.  
  19.     # return the letter back at the right ascii value
  20.     return chr(i + ord('a'))
  21.  
  22. def polyalphabetic(w, k):
  23.     k_index = 0
  24.     result = []
  25.     for char in w:
  26.         if (not char.isalpha()):
  27.             # char isn't alphanumeric, so we don't shift it at all
  28.             result.append(char)
  29.             continue
  30.         result.append(shift(char, k[k_index]))
  31.  
  32.         k_index += 1      # go to the next key
  33.         k_index %= len(k) # if we're past the end, go back to 0
  34.  
  35.     return "".join(result)
  36.  
  37. if __name__ == "__main__":
  38.     print polyalphabetic(word, key)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement