Caesar Cipher in Python

PythonServer Side ProgrammingProgramming

Suppose we have a lowercase alphabet string s, and an offset number say k. We have to replace every letter in s with a letter k positions further along the alphabet. We have to keep in mind that when the letter overflows past a or z, it gets wrapped around the other side.

So, if the input is like "hello", k = 3, then the output will be "khoor"

To solve this, we will follow these steps −

  • Define a function shift(). This will take c

  • i := ASCII of (c) - ASCII of ('a')

  • i := i + k

  • i := i mod 26

  • return character from ASCII (ASCII of ('a') + i)

  • From the main method, do the following −

  • ret := for each character c in s, make a list of elements by calling shift(c)

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s, k):
      def shift(c):
         i = ord(c) - ord('a')
         i += k
         i %= 26
         return chr(ord('a') + i)

      return "".join(map(shift, s))

ob = Solution()
print(ob.solve("hello", 3))

Input

"hello", 3

Output

khoor
raja
Published on 02-Sep-2020 13:19:27
Advertisements