如何找到由完全相互面对的字母组成的单词? (蟒蛇)

时间:2013-04-17 09:08:06

标签: python

我尝试了很多方法来制作这个功能,但总是失败了。

例如:

  

“他是男孩。”

     

“欺负他”

问题的第一件事就是找到配对这样的“男孩”,“b”配对“y”和“o”配对,如果“欺负”,“b”配对“y”和“u”带“l”但第一个“l”未配对

然后,单词中的第一个字母和单词中的最后一个字母必须符合此要求:

word1= ('a','b','c','d','e','f','g','h','i','j','k','l','m')
word2= ('z','y','x','w','v','u','t','s','r','q','p','o','n')

“a”必须只与“z”配对,“b”必须只与“y”配对,依此类推

因此“他是男孩”的输出只是“男孩”,因为“h”不与“e”配对,“i”不与“s”配对,“t”不与“e”配对/ p>

然而,对于“欺负”虽然包括“b”和“y”但不包括“u”和“l”,所以不会有“欺负他”的输出

4 个答案:

答案 0 :(得分:1)

>>> tr = str.maketrans('abcdefghijklm', 'zyxwvutsrqpon')
>>> def isPalindromyWord(word):
        t = word.translate(tr)
        return t == t[::-1]
>>> s = 'he is the boy'
>>> list(filter(isPalindromyWord, (word for word in s.split(' '))))
['boy']

答案 1 :(得分:0)

>>> from string import punctuation
>>> text = "he is the boy."
>>> word1 = ('a','b','c','d','e','f','g','h','i','j','k','l','m')
>>> word2 = ('z','y','x','w','v','u','t','s','r','q','p','o','n')
>>> d = dict(zip(word1 + word2, word2 + word1))
>>> words = (w.strip(punctuation) for w in text.split())
>>> [w for w in words if d[w[0]] == w[-1]]
['boy']

答案 2 :(得分:0)

这是一个尝试:

>>> word1= ('a','b','c','d','e','f','g','h','i','j','k','l','m')
>>> word2= ('z','y','x','w','v','u','t','s','r','q','p','o','n')
>>> [w for w in s.split() if w[0] in word1 and w[-1] in word2 and word1.index(w[0]) == word2.index(w[-1])]
['boy']

答案 3 :(得分:0)

word1word2压缩到名为alphabets

的字符串中
alphabets = 'abcdefghijklmnopqrstuvwxyz'

以下功能可以满足您的需求(不是很漂亮)

def find_match(s): 
    split_s=s.lower().split(' ')
    matches = []
    for word in split_s: 
        found = 0
        sum = 0
        for i in xrange(0,len(word)//2):
            sum += 1
            if alphabets.index(word[i])+alphabets.index(word[len(word)-i-1]) == 25:
                found += 1
        if found == sum: 
            matches.append(word)
    return matches

输出

>>> find_match('bully him')
[]
>>> find_match('the boy wants ')
['boy']
>>> find_match('the boy wants aazz')
['boy', 'aazz']
>>> find_match('the boy wants abayz')
['boy', 'abayz']
>>> find_match('the boy wants abasz')
['boy']

拆分输入字符串以提取单词。然后,对于每个单词,将第一个和最后一个字母(依此类推)与它们在字母表中的实际位置进行比较(alphabet中其索引的总和应为25,即{{1}中的最大索引}})。如果该单词的每个字母都匹配,请将该单词添加到匹配单词列表中