Friday, December 27, 2024
Google search engine
HomeLanguagesEncrypt the String according to the given algorithm in Python

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.

Python3




# 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:

  • For indexing, through a string, we have a provision of three arguments. The indexing is done with integers (not float values) and intended with close brackets.
  • The first argument is for the starting point, the second argument is for jump though the sub-string and third argument is the endpoint.
  • So in the above reverse-string method, we keep the first argument empty , so the indexing would begin from the first sub-string , the second argument is left empty so there would be not jumping through sub-strings and endpoint would be -1 which would result in the compiler to manipulate and reverse the given input.

Approach : Using index() method

Python3




# 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
RELATED ARTICLES

Most Popular

Recent Comments