Python – 字符串的镜像
给定一个字符串,执行它的镜像,如果不能使用英文字符镜像,则返回“Not possible”。
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.
方法:使用循环+循环字典
这是可以执行此任务的一种方式。在此,我们为所有有效的可镜像英文字符构建查找字典,然后从它们执行访问任务。
Python3
# Python3 code to demonstrate working of
# Mirror Image of String
# Using Mirror Image of String
# initializing strings
test_str = 'void'
# printing original string
print("The original string is : " + str(test_str))
# initializing mirror dictionary
mir_dict = {'b':'d', 'd':'b', 'i':'i', 'o':'o', 'v':'v', 'w':'w', 'x':'x'}
res = ''
# accessing letters from dictionary
for ele in test_str:
if ele in mir_dict:
res += mir_dict[ele]
# if any character not present, flagging to be invalid
else:
res = "Not Possible"
break
# printing result
print("The mirror string : " + str(res))
输出
The original string is : void
The mirror string : voib