Python – Index Mapping Cypher
Last Updated :
15 Apr, 2023
Sometimes, while working with Python, we can have problems in security or gaming domain, in which we need to create certain cyphers, they can be different types of. This includes Index Mapping Cypher in which we pass a string of integers and we get element characters in that order. Lets discuss certain ways to construct this. Method #1 : Using loop This is brute force manner in which this can be constructed. In this, we manually check for each character and map it as index number to value in string.
Python3
test_str = "geeksforgeeks"
print ( "The original string is : " + test_str)
cyp_str = "53410"
res = ""
temp = [ int (idx) for idx in cyp_str]
for ele in temp:
res + = test_str[ele]
print ( "The deciphered value string : " + str (res))
|
Output :
The original string is : geeksforgeeks
The deciphered value string : fkseg
Method #2 : Using join() + loop The combination of above functions can also be used to solve this problem. In this, we reduce a final loop by using join() to construct decipher string.
Python3
test_str = "geeksforgeeks"
print ( "The original string is : " + test_str)
cyp_str = "53410"
res = [test_str[ int (idx)] for idx in cyp_str]
res = ''.join(res)
print ( "The deciphered value string : " + str (res))
|
Output :
The original string is : geeksforgeeks
The deciphered value string : fkseg
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Method 3 : using list comprehension.
step-by-step approach
Initialize the string and the cipher string.
Convert the cipher string into a list of integers using list comprehension.
Use another list comprehension to map the indexes of the original string to the corresponding indexes in the cipher list.
Join the resulting list of characters into a single string.
Print the deciphered string.
Python3
test_str = "geeksforgeeks"
print ( "The original string is : " + test_str)
cyp_str = "53410"
res = ''.join([test_str[ int (idx)] for idx in cyp_str])
print ( "The deciphered value string : " + str (res))
|
Output
The original string is : geeksforgeeks
The deciphered value string : fkseg
The time complexity of this method is O(n), where n is the length of the cipher string.
The auxiliary space required is O(n), since we need to create a list of integers corresponding to the cipher string.
Share your thoughts in the comments
Please Login to comment...