Skip to content Skip to sidebar Skip to footer

How To Find Words That Made Up Of Letter Exactly Facing Each Other? (python)

I have tried so many ways to make the function but it always failed. for examples: 'he is the boy.' 'bully him' The first thing that is asked on the question is to find words th

Solution 1:

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

Solution 2:

>>>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']

Solution 3:

Here is a try:

>>>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']

Solution 4:

Condensing your word1 and word2 into a string called alphabets

alphabets = 'abcdefghijklmnopqrstuvwxyz'

The following function will do what you want (It is not very pretty)

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

Output

>>> 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']

Split your input string to extract words. Then for each word compare the first and the last letter (and so on) to their actual positions in the alphabets (The sum of their indices in alphabet should be 25,i.e. max index in alphabets). If every letter of the word is matched, add the word to a list of matched words

Post a Comment for "How To Find Words That Made Up Of Letter Exactly Facing Each Other? (python)"