Advertisement
Guest User

Caesar Cipher

a guest
Sep 29th, 2012
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. ####method 1
  2. phrase = raw_input("Enter sentence to encrypt: ")
  3. shift = input("Enter shift value: ")
  4.  
  5. encoded = ''
  6. for c in phrase:
  7.     if c in 'abcdefghijklmnopqrstuvwxyz':
  8.         encoded += chr((ord(c)-ord('a')+shift)%26 + ord('a'))
  9.     elif c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
  10.         encoded += chr((ord(c)-ord('A')+shift)%26 + ord('A'))
  11.     else:
  12.         encoded += c
  13.  
  14. print "The encoded phrase is: " + encoded
  15.  
  16. #### method 2:
  17. #Modularisation (Reforming aka refactoring the code to make functions to replace repeated code)
  18.  
  19. #Using your method, one step at a time
  20. #mod=26 is a default value, this is what it's given if you don't give it a different value
  21. def shiftChar(char, base, shift, mod=26):
  22.         char -= base
  23.         char += shift
  24.         char %= mod
  25.         char +=base
  26.         return char
  27.  
  28. #Or bringing all of the steps into one line
  29. def shiftCharCondensed(char, base, shift, mod=26):
  30.     return ((char-base)+shift)%mod+base
  31.  
  32. phrase = raw_input("Enter sentence to encrypt: ")
  33. shift = input("Enter shift value: ")
  34.    
  35. encoded = ''
  36. for c in phrase:
  37.     ascii = ord(c)
  38.     if 97 <= ascii < (97+26):
  39.         ascii = shiftChar(ascii, 97, shift)
  40.     elif 65 <= ascii < (65+26):
  41.         ascii = shiftChar(ascii, 65, shift)
  42.     c = chr(ascii)
  43.     encoded += c
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement