如果它只包含可反映的字母,则反转一个字符串

时间:2014-11-11 03:58:25

标签: python string

这是问题所在。不,这不是自学的作业。

我正在尝试以下问题:

字符串誓言的镜像是字符串wov,镜像木头是字符串boow。但是,字符串床的镜像不能表示为字符串,因为e的镜像不是有效字符。 字母表中的镜像是有效字符的字符是:b,d,i,o,v,w和x。开发函数mirror(),它接受一个字符串并返回其镜像,但前提是镜像可以用字母表中的字母表示。

**我的代码**

def mirror(word):
    '''returns mirror image of word but if it can be represented
       using letters in the alphabet'''
    for i in range (0,len(word)):
        if i == 'bdiovwx':
            print(str(word.reverse))
        else:
            print ('NOPE')

我得到的结果是什么。就像我执行程序一样,没有打印。

有什么想法吗?

谢谢

3 个答案:

答案 0 :(得分:3)

你不需要for循环。从本质上讲,您正在测试该单词的所有字符是否属于'bdiovwx'中的一个字符,因此,您可以正好检查fr - 单词中字符集之间的子集关系,以及{{ 1}}。

此外,字符串在python中没有反向方法,因此您可以使用技巧'bdiovwx'打印其反向。

"string"[::-1]

答案 1 :(得分:1)

请注意' d'反映了一个''和' b'反映了一个'在镜子里:))

def mirror(word):
    letters = list("bdiovwx")
    reflect_letters = list("dbiovwx")
    if set(word).issubset(letters):
        print ''.join([reflect_letters[letters.index(x)] for x in word[::-1]])
    else:
        print "NOPE!"

答案 2 :(得分:1)

通过修复算法,您可以获得结果。您只需循环遍历项目,添加要设置的所有元素并在以后比较它,如果它包含在您定义的字母集'bdiovwx'中,notFound用于在您找到变量时停止迭代不属于您定义的'bdiovwx'

的公认集合

word[::-1]产生反转词

def mirror(word):
    '''returns mirror image of word but if it can be represented
       using letters in the alphabet'''
    i,notFound=0,True
    D=set()
    while notFound and i < len(list(word)):
        if word[i] not in list('bdiovwx'):
            notFound= False
        D.add(word[i])
        i+=1
    if notFound and D.issubset(set(list('bdiovwx'))):
        print word[::-1]
    else:
        print ('NOPE')

您还可以使用ALL运算符来验证单词中的所有字符都在'bdiovwx'中,如果它是True,则打印反向,否则;你打印None

def mirror(word):
    if all(x for x in list(word) if x in list('bdiovwx')):
        print word[::-1]
    else:
        print ('NOPE')
相关问题