 GeeksforGeeks App
Open App Browser
Continue

# 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”
Explanation: Here “refer”, “madam”, “level” are the palindromic words. Sorting them generates the sequence {“level”, “madam”, “refer”}.

Input: S = “refer to dad”

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: Follow the steps below to solve the problem:

Below is the implementation of the above approach:

## Python3

 `# Python implementation of above program` `# Function to check if a``# string is a palindrome or not`  `def` `palindrome(string):``    ``if``(string ``=``=` `string[::``-``1``]):``        ``return` `True``    ``else``:``        ``return` `False` `# Function to print the updated sentence`  `def` `printSortedPalindromes(sentence):` `    ``# Stores palindromic words``    ``newlist ``=` `[]` `    ``# Stores the words split by spaces``    ``lis ``=` `list``(sentence.split())` `    ``# Traversing the list``    ``for` `i ``in` `lis:` `        ``# If current word is palindrome``        ``if``(palindrome(i)):` `            ``# Update newlist``            ``newlist.append(i)` `    ``# Sort the words in newlist``    ``newlist.sort()` `    ``# Pointer to iterate newlis``    ``j ``=` `0` `    ``# Traverse the list``    ``for` `i ``in` `range``(``len``(lis)):` `        ``# If current word is palindrome``        ``if``(palindrome(lis[i])):` `            ``# Replacing word with``            ``# current word in newlist``            ``lis[i] ``=` `newlist[j]` `            ``# Increment j by 1``            ``j ``=` `j ``+` `1` `    ``# Print the updated sentence``    ``for` `i ``in` `lis:``        ``print``(i, end``=``" "``)`  `# Driver Code` `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)

## Python3

 `# Python implementation of above program`  `# Function to print the updated sentence``def` `printSortedPalindromes(sentence):` `    ``# Stores palindromic words``    ``newlist ``=` `[]` `    ``# Stores the words split by spaces``    ``lis ``=` `list``(sentence.split())``    ``newlist ``=` `list``(``filter``(``lambda` `x: x ``=``=` `x[::``-``1``], lis))` `    ``# Sort the words in newlist``    ``newlist.sort()` `    ``# Pointer to iterate newlis``    ``j ``=` `0` `    ``# Traverse the list``    ``for` `i ``in` `range``(``len``(lis)):` `        ``# If current word is palindrome``        ``if``(lis[i] ``=``=` `lis[i][::``-``1``]):` `            ``# Replacing word with``            ``# current word in newlist``            ``lis[i] ``=` `newlist[j]` `            ``# Increment j by 1``            ``j ``=` `j ``+` `1` `    ``# Print the updated sentence``    ``for` `i ``in` `lis:``        ``print``(i, end``=``" "``)`  `# Driver Code` `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(nlogn)
Auxiliary Space: O(n)

Method #3: Using regular expressions:

Algorithm:

1. Split the given sentence into words using regular expressions.
2. Create a list of palindromic words.
3. Sort the list of palindromes in lexicographically ascending order.
4. Replace the palindromic words in the original sentence with sorted palindromes.
5. Print the updated sentence.

## Python3

 `import` `re`  `def` `printSortedPalindromes(sentence):``    ``# Use regular expressions to split the sentence into words``    ``words ``=` `re.findall(r``'\b\w+\b'``, sentence)``    ``# Create a list of palindromic words``    ``palindromes ``=` `[word ``for` `word ``in` `words ``if` `word ``=``=` `word[::``-``1``]]``    ``# Sort the list of palindromes``    ``palindromes.sort()``    ``# Replace palindromic words in the original sentence with sorted palindromes``    ``for` `i, word ``in` `enumerate``(words):``        ``if` `word ``=``=` `word[::``-``1``]:``            ``words[i] ``=` `palindromes.pop(``0``)``    ``# Print the updated sentence``    ``print``(``' '``.join(words))`  `# Driver code``sentence ``=` `"please refer to the madam to know the level"``printSortedPalindromes(sentence)``# This code is contributed by Jyothi pinjala`

Output

`please level to the madam to know the refer`

Time complexity:
The regular expression to split the sentence into words has a time complexity of O(n), where n is the length of the sentence.

Auxiliary Space:
The regular expression to split the sentence into words and the list of palindromic words both require additional space to store intermediate data, but the space usage is proportional to the size of the input and the number of palindromes, respectively. Therefore, the space complexity of the function is O(n + m).has context menu

Method #4: Using reduce():

1. Define a function called “update_sentence” that takes two arguments: a list of palindromic words and a word.
If the word is a palindrome, append it to the list of palindromic words and return the updated list.
2. Define another function called “printSortedPalindromes” that takes a sentence as its argument.
Use regular expressions to split the sentence into words and store them in a list called “words”.
3. Apply the reduce function to the list of words and the update_sentence function to create a list of palindromic words.
4. Sort the list of palindromic words in ascending order.
5. Loop through the list of words and replace any palindromic words with the corresponding word from the sorted list of palindromic words.
6. Print the updated sentence.
7. Call the “printSortedPalindromes” function with a sample sentence to test the code.

## Python3

 `import` `re``from` `functools ``import` `reduce`  `def` `update_sentence(palindromes, word):` `    ``if` `word ``=``=` `word[::``-``1``]:``        ``palindromes.append(word)``    ``return` `palindromes`  `def` `printSortedPalindromes(sentence):``    ``# Use regular expressions to split the sentence into words``    ``words ``=` `re.findall(r``'\b\w+\b'``, sentence)``    ``# Create a list of palindromic words``    ``palindromes ``=` `reduce``(update_sentence, words, [])``    ``# Sort the list of palindromes``    ``palindromes.sort()``    ``# Replace palindromic words in the original sentence with sorted palindromes``    ``for` `i, word ``in` `enumerate``(words):``        ``if` `word ``=``=` `word[::``-``1``]:``            ``words[i] ``=` `palindromes.pop(``0``)``    ``# Print the updated sentence``    ``print``(``' '``.join(words))`  `# Driver code``sentence ``=` `"please refer to the madam to know the level"``printSortedPalindromes(sentence)` `# This code is contributed by Rayudu.`

Output

`please level to the madam to know the refer`

Time complexity: O(n log n) because of the sorting operation performed on the list of palindromes.
Auxiliary space: O(n) because the code uses a list to store the palindromes and another list to store the words. The reduce function uses constant space because it does not create any new lists.

My Personal Notes arrow_drop_up