Python mirrored string function

前端 未结 5 496
攒了一身酷
攒了一身酷 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: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
    

提交回复
热议问题