I\'m trying to develop a function mirror()
that takes a string and returns its mirrored string but only if the mirrored string can be represented using \"mirror
You can look up the replacement characters in a generator expression as you iterate over the string (in reverse). You can reassemble characters into a string with str.join
. I suggest using the "Easier to Ask for Forgiveness than Permission" idiom to handle invalid characters (don't check up front if the character is valid, but instead use try
and catch
statements to handle the exception raised if it is not).
def mirror(s):
mir={'b':'d','d':'b','o':'o','p':'q','q':'p','v':'v','w':'w','x':'x'}
try:
return "".join(mir[c] for c in reversed(s))
except KeyError:
return "INVALID"