Python mirrored string function

前端 未结 5 494
攒了一身酷
攒了一身酷 2021-01-16 12:45

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

相关标签:
5条回答
  • 2021-01-16 13:27

    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.

    0 讨论(0)
  • 2021-01-16 13:30
    def mirror(lst):
      return lst + lst[-2::-1]
    
    print(mirror([0, 2, 4, 6]))
    
    0 讨论(0)
  • 2021-01-16 13:37

    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"
    
    0 讨论(0)
  • 2021-01-16 13:38

    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
    
    0 讨论(0)
  • 2021-01-16 13:41

    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).

    0 讨论(0)
提交回复
热议问题