Open In App

Encrypt the String according to the given algorithm in Python

Given a string s, the task is to encrypt the string in the following way. Let the string be “apple”.

Step 1: Reverse the input: “elppa”



Step 2: Replace all vowels using the following chart:

a => 0
e => 1
i => 2
o => 2
u => 3
Resultant string - "1lpp0"

Step 3: Add “aca” to the end of the word:



Resultant String: "1lpp0aca"

Examples:

Input: banana
Output: 0n0n0baca"

Input: karaca
Output: 0c0r0kaca"

Input: burak
Output: k0r3baca

Approach:

  1. Create a dictionary which stores values so that it can be easily accessed.
  2. Reverse the string by indexing method.
  3. Loop through the word to replace vowels.

Below is the implementation.




# Create an input field
encrypt = "banana"
 
# Create a dictionary to store keys
# and values
dict = {"a": "0", "e": "1",
        "i": "2", "o": "2",
        "u": "3"}
 
# Reverse the string
num = encrypt[::-1]
 
# Replace vowels using loops
for i in dict:
    num = num.replace(i, dict[i])
 
# f- strings which improves readability
print(f"{num}aca")

Output
0n0n0baca

Let’s understand the above code:

Approach : Using index() method




# Create an input field
encrypt = "banana"
 
# Reverse the string
num = encrypt[::-1]
 
vow="aeiou"
x=""
# Replace vowels using loops
for i in num:
    if(i in vow):
        x+=str(vow.index(i))
    else:
        x+=i
print(x+"aca")

Output
0n0n0baca

Article Tags :