0

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

举些例子:

“他就是那个男孩。”

“欺负他”

问题的第一件事是找到与“boy”配对的单词,“b”将与“y”配对,“o”未配对,如果“bully”,“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”配对,依此类推

所以“he is the boy”的输出只有“boy”,因为“h”不与“e”配对,“i”不与“s”配对,“t”不与“e”配对

但是,对于“bully”,虽然包括了“b”和“y”,但不包括“u”和“l”,所以不会有“bully him”的输出

4

4 回答 4

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']
于 2013-04-17T12:11:42.340 回答
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']
于 2013-04-17T09:19:02.707 回答
0

将你的word1and压缩word2成一个名为的字符串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,即最大索引 in alphabets)。如果单词的每个字母都匹配,则将该单词添加到匹配单词列表中

于 2013-04-17T11:45:21.527 回答
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']
于 2013-04-17T09:13:07.473 回答