可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 "mirrored" letters in the given string.
For example,
>>>mirror('vow') 'wov' >>>mirror('wood') 'boow' >>>mirror('bed') 'INVALID'
That is, a mirrored b
is a d
. The letter e
does not have any mirrored equivalent.
So far I've started with this
def mirror(s): return str[::-1]
How can I extend this to work for whole words?
回答1:
Firstly, you should have a dictionary that stores the mirror image of every character.
mirrored = {'b': 'd', 'd': 'b', 'v': 'v', ...}
So, for every string that we need to produce a mirror of, you should check that every character in the given string has it's mirrored value in the string itself.
given_string = input() valid = True for char in given_string: if not mirrored[char] in given_string: valid = False break if valid: # generate mirrored string
The reversed string approach you are using is right. Just add above check & you'll be on your way to generate mirrored strings!
Another way to do this, would be using a simple Python hack of for
...else
given_string = input() valid = True for char in given_string: if not mirrored[char] in given_string: break else: # generate mirrored string
回答2:
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"
回答3:
You have the right idea about iterating through the given letters in reverse order. However, you cannot necessarily just give each letter itself as its own mirrored version. An example would be b
and d
, which are mirror versions of each other.
The simplest way if you're learning to program would be to use a for
loop to move backwards through the given letters, and use some if
statements for each letter to determine the mirrored letter (if there is one).
回答4:
Try this:
def mirror(s): mir = {'b': 'd', 'd': 'b', 'o': 'o', 'p': 'q', 'q': 'p', 'v': 'v', 'w': 'w', 'x': 'x'} if not set(s).issubset(mir.keys()): return 'INVALID' return ''.join(map(lambda x: mir[x], s[::-1]))
Here use set
to judge whether the chars in str s
is valid or not.