Encrypt the String according to the given algorithm in Python
Last Updated :
22 Sep, 2022
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:
- Create a dictionary which stores values so that it can be easily accessed.
- Reverse the string by indexing method.
- Loop through the word to replace vowels.
Below is the implementation.
Python3
encrypt = "banana"
dict = { "a" : "0" , "e" : "1" ,
"i" : "2" , "o" : "2" ,
"u" : "3" }
num = encrypt[:: - 1 ]
for i in dict :
num = num.replace(i, dict [i])
print (f "{num}aca" )
|
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
encrypt = "banana"
num = encrypt[:: - 1 ]
vow = "aeiou"
x = ""
for i in num:
if (i in vow):
x + = str (vow.index(i))
else :
x + = i
print (x + "aca" )
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...