Python – Mirror Image of String
Last Updated :
24 Apr, 2023
Given a String, perform its mirror imaging, return “Not Possible” if mirror image not possible using english characters.
Input : test_str = ‘boid’ Output : doib Explanation : d replaced by b and vice-versa as being mirror images. Input : test_str = ‘gfg’ Output : Not Possible Explanation : Valid Mirror image not possible.
Method : Using loop + lookup dictionary
This is one way in which this task can be performed. In this, we construct lookup dictionary for all valid mirrorable english characters, then perform task of access from them.
Python3
test_str = 'void'
print ( "The original string is : " + str (test_str))
mir_dict = { 'b' : 'd' , 'd' : 'b' , 'i' : 'i' , 'o' : 'o' , 'v' : 'v' , 'w' : 'w' , 'x' : 'x' }
res = ''
for ele in test_str:
if ele in mir_dict:
res + = mir_dict[ele]
else :
res = "Not Possible"
break
print ( "The mirror string : " + str (res))
|
Output
The original string is : void
The mirror string : voib
Time Complexity: O(n)
Space Complexity: O(n)
Method 2 : using string slicing to reverse the string and a lookup dictionary to replace the mirrored characters.
step by step approach:
Define the input string.
Define a dictionary that maps mirrored characters to their respective values.
Reverse the input string using string slicing.
Iterate over the reversed string and replace each character with its mirror image from the dictionary. If the character is not present in the dictionary, set the result string to “Not Possible” and break the loop.
Reverse the result string back to its original order.
Print the original and mirror strings.
Python3
test_str = 'void'
mir_dict = { 'b' : 'd' , 'd' : 'b' , 'i' : 'i' , 'o' : 'o' , 'v' : 'v' , 'w' : 'w' , 'x' : 'x' }
rev_str = test_str[:: - 1 ]
res = ''
for ele in rev_str:
if ele in mir_dict:
res + = mir_dict[ele]
else :
res = "Not Possible"
break
mir_str = res[:: - 1 ]
print ( "The original string is : " + str (test_str))
print ( "The mirror string : " + str (mir_str))
|
Output
The original string is : void
The mirror string : voib
The time complexity of this approach is O(n) as it involves iterating over the string only once.
The auxiliary space complexity is also O(n) because we create a new reversed string and a new mirrored string.
Please Login to comment...