- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements