Program to encrypt a string using Vigenere cipher in Python


Suppose we have a lowercase alphabet string text, and have another string called key. We have to find a new string where every letter in text[i] is moved to the right side with offset key[i]. Here the offset represented by key[i]'s position in the alphabet (A=0, B=1 etc.) If the letter overflows, it gets wrapped around the other side.

So, if the input is like text = "code", key = "team", then the output will be "vsdq"

To solve this, we will follow these steps −

  • cip := a new list
  • start := ASCII of 'a'
  • for each l from text and k from key, do
    • shift := (ASCII of k) - start
    • pos := start +((ASCII of l) - start + shift) mod 26
    • insert character of pos at the end of cip
  • join strings of cip and return

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, text, key):
      cip = []
      start = ord('a')
      for l, k in zip(text, key):
         shift = ord(k) - start
         pos = start + (ord(l) - start + shift) % 26
         cip.append(chr(pos))
      return ''.join([l for l in cip])
ob = Solution()
text = "code"
key = "team"
print(ob.solve(text, key))

Input

"code", "team"

Output

vsdq

Updated on: 05-Oct-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements