fork download
  1. # Playground for https://stackoverflow.com/a/56143306/11458991
  2.  
  3.  
  4. import string
  5.  
  6.  
  7. def letter_index(letter):
  8. """Determines the position of the given letter in the English alphabet
  9.  
  10. 'a' -> 0
  11. 'A' -> 0
  12. 'z' -> 25
  13. """
  14. if letter not in string.ascii_letters:
  15. raise ValueError("The argument must be an English letter")
  16.  
  17. if letter in string.ascii_lowercase:
  18. return ord(letter) - ord('a')
  19. return ord(letter) - ord('A')
  20.  
  21.  
  22. def caesar(s):
  23. """Ciphers the string s by shifting 'A'->'B', 'B'->'D', 'C'->'E', etc
  24.  
  25. The shift is cyclic, i.e. 'A' comes after 'Z'.
  26. """
  27. ret = ""
  28. for letter in s:
  29. index = letter_index(letter)
  30. new_index = 2*index + 1
  31. if new_index >= len(string.ascii_lowercase):
  32. # The letter is shifted farther than 'Z'
  33. new_index %= len(string.ascii_lowercase)
  34. new_letter = chr(ord(letter) - index + new_index)
  35. ret += new_letter
  36.  
  37. return ret
  38.  
  39.  
  40. print('caesar("ABC"):', caesar("ABC"))
  41. print('caesar("abc"):', caesar("abc"))
  42. print('caesar("XYZ"):', caesar("XYZ"))
Success #stdin #stdout 0.02s 27768KB
stdin
Standard input is empty
stdout
caesar("ABC"): BDF
caesar("abc"): bdf
caesar("XYZ"): VXZ