简体   繁体   中英

print the mirror image of string in Python3

I'm trying to develop function mirror() that takes a string and returns its mirror image but only if the mirror image can be represented using letter in the alphabet.

>>>mirror('vow')
'wov'
>>>mirror('bed')
'INVALID'

My code doesn't give me correct answers. Thanks for any tips!

def mirror(word):
    a={'b':'d','d':'b', 'i':'i', 'o':'o','v':'v','w':'w','x':'x'}
    res=''

    for letter in word:
        if letter in a:
            res=res+a[letter]
            return res

        else:
            return 'INVALID'

    return res

The return res in the if statement needs to be removed, the program currently exits if the first letter is a match and returns that.

This should work

    def mirror(word):
    a={'b':'d','d':'b', 'i':'i', 'o':'o','v':'v','w':'w','x':'x'}
    res=''

    for letter in word:
        if letter in a:
            res += a[letter]


        else:
            return 'INVALID'

    return res

print(mirror("bob"))

return will break out of your function so once it finds the first letter it will stop running.

I also changed

res=res+a[letter]

to....

res += a[letter]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM