0

I need to find the string in a sentence whose reverse is also present in the same sentence and return that string.

Suppose the sentence is:

illusion never changed into something real wide awake and i can see the perfect sky ees torn you are a little late I'm already torn

Here we can see that "see" has a reverse present as "ees"

So the output should be "see"

Please guide me how to do that.

YusufUMS
  • 1,506
  • 1
  • 12
  • 24
  • Look for instance at : https://stackoverflow.com/questions/17331290/how-to-check-for-palindrome-using-python-logic – Demi-Lune Apr 25 '19 at 06:19
  • 2
    @Rakesh, this question is not a duplicate, since the question you are referring to resolves just a small part of the problem, but the bigger problem is finding all palindromes within the string! – Devesh Kumar Singh Apr 25 '19 at 06:50

2 Answers2

0

You can try this.

mystr = "illusion never changed into something real wide awake and i can see the perfect sky ees torn you are a little late I'm already torn"

def reverse(word):
    letter = list(word)
    length = len(letter)
    y = []
    for x,w in enumerate(letter):
        y.append("".join(letter[(length-1)-x]))
    return("".join(yy for yy in y))


words = mystr.split()
for word in words:
    if (reverse(word)) in words and len(word) > 1:   # len(word)>1 is for ignoring a word that contains only one letter, e.g. 'I' and 'a'.
        print ("'" + word + "' is the reverse of '" + reverse(word) + "'")

Output:

'see' is the reverse of 'ees'
'ees' is the reverse of 'see'

You can also try the simpler one as suggested by @Nuhman.

mystr = "illusion never changed into something real wide awake and i can see the perfect sky ees torn you are a little late I'm already torn"

words = mystr.split()
for word in words:
    if word[::-1] in words and len(word) > 1:
        print ("'" + word + "' is the reverse of '" + reverse(word) + "'")

Output:

'see' is the reverse of 'ees'
'ees' is the reverse of 'see'
YusufUMS
  • 1,506
  • 1
  • 12
  • 24
0

Use word[::-1] to reverse the word and if reverse is present in list of words store it another list.

hello = "illusion never changed into something real wide awake and i can see the perfect sky ees torn you are a little late I'm already torn"

words = hello.split(" ")

reverse_words = []
for word in words:
    if word[::-1] in words and len(word)>1 and word[::-1] not in reverse_words:
        reverse_words.append(word)

print(reverse_words)

Output:

['see']
Sociopath
  • 13,068
  • 19
  • 47
  • 75