how to find words in a sentence that have even reverse of those words in python

chits :

I would like to get find all the words that have reversed words in a same sentence. How ever, the code I got finds only first occurrence of the word. in my sentence "i am going to eat ma and tae will also go", I should get an output of am( ma is reversed word) and eat( tae is the reversed word). I only get am..how can i modify this code to get all the words that have reversed words in it i.e. both am and eat.

input_str='i am going to eat ma and tae will also go'
word=input_str.split()
def isReverseEqual(s1, s2): 

    # If both the strings differ in length 
    if len(s1) != len(s2): 
        return False

    l = len(s1) 

    for i in range(l): 

        # In case of any character mismatch 
        if s1[i] != s2[l-i-1]: 
            return False
    return True
def getWord(str, n): 
    reverse=[]
    # Check every string 
    for i in range(n-1): 

        # Pair with every other string 
        # appearing after the current string 
        for j in range(i+1, n): 

            # If first string is equal to the 
            # reverse of the second string 
            if (isReverseEqual(str[i], str[j])): 
                reverse.append(str[i])
                return reverse 


    # No such string exists 
    return "-1"
print(getWord(word, len(word))) 

Output: ['am','eat'] is what expected.

kederrac :

you can use:

words = input_str.split()

s = set()
result = set()
for w in words:
    r = w[::-1]
    if r in s:
        result.add(r)
    else:
        s.add(w)

list(result)

output:

['am', 'eat']

this is O(n) time complexity solution, so you have to get first the words and iterate through them, each time you have a new word you are adding him to a set, if the reverse is already in the set you are adding the reverse to the result

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216575&siteId=1