Thursday, April 1, 2021

Published April 01, 2021 by Anonymous with 0 comment

Python program to sort Palindrome Words in a Sentence

Python program to sort Palindrome Words in a Sentence

Given a string S representing a sentence, the task is to reorder all the palindromic words present in the sentence in sorted order.

Examples:

Input: S = “Please refer to the madam to know the level”
Output: Please level to the madam to know the refer
Explanation: Here “refer”, “madam”, “level” are the palindromic words. Sorting them generates the sequence {“level”, “madam”, “refer”}.

Input: S = “refer to dad”
Output: dad to refer

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 printSortedPalindromes(sentence):

    

    

    newlist = []

      

    

    lis = list(sentence.split())

      

    

    for i in lis:

        

        

        if(palindrome(i)):

            

            

            newlist.append(i)

  

    

    newlist.sort()

  

    

    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 = "please refer to the madam to know the level"

  

printSortedPalindromes(sentence)

Output:
please level to the madam to know the refer

Time Complexity : O(N * logN)
Auxiliary Space : O(N)


Let's block ads! (Why?)


Original page link

Best Cool Tech Gadgets

Top favorite technology gadgets
      edit

0 comments:

Post a Comment