Modify a sentence by reversing order of occurrences of all Palindrome Words

Modify a sentence by reversing order of occurrences of all Palindrome WordsGiven a string S representing a sentence, the task is to reverse the order of all palindromic words present in the sentence.Examples:Input: S = “mom and dad went to eye hospital”Output: eye and dad went to mom hospitalExplanation: All palindromic words present in the string are “mom”, “dad” and “eye“, in the order of their occurrence. Reversing the order of their occurrence generates the sequence {“eye”, “dad”, “mom”}. Therefore, the modified string is “eye and dad went to mom hospital”.Input : S = “wow it is next level”Output: level it is wow.Approach: Follow the steps below to solve the problem:Below is the implementation of the above approach:Python3  def palindrome(string):        if(string == string[::-1]):        return True    else:        return False  def printReverse(sentence):            newlist = []              lis = list(sentence.split())              for i in lis:                        if(palindrome(i)):                                      newlist.append(i)          newlist.reverse()          j = 0              for i in range(len(lis)):                        if(palindrome(lis[i])):                                    lis[i] = newlist[j]                                      j = j + 1          for i in lis:        print(i, end =” “)      sentence = “mom and dad went to eye hospital”printReverse(sentence)Output:
eye and dad went to mom hospital
Time Complexity: O(N)Auxiliary Space: O(1)Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.