Python program to sort Palindrome Words in a Sentence
Last Updated :
03 Apr, 2023
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
# 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)
Method #2: Using lambda functions
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)
Outputplease level to the madam to know the refer
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Method #3: Using regular expressions:
Algorithm:
- Split the given sentence into words using regular expressions.
- Create a list of palindromic words.
- Sort the list of palindromes in lexicographically ascending order.
- Replace the palindromic words in the original sentence with sorted palindromes.
- 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
Outputplease 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():
- 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. - 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". - Apply the reduce function to the list of words and the update_sentence function to create a list of palindromic words.
- Sort the list of palindromic words in ascending order.
- Loop through the list of words and replace any palindromic words with the corresponding word from the sorted list of palindromic words.
- Print the updated sentence.
- 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.
Outputplease 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.
Similar Reads
Python program to count words in a sentence
In this article, we will explore different methods for counting words in a sentence. The split() method is one of the simplest and most efficient ways to count words in a sentence.Pythons = "Python is fun and versatile." # Counting words word_count = len(s.split()) print(word_count) Output5 Explanat
2 min read
Python program to find the longest word in a sentence
In this article, we will explore various methods to find the longest word in a sentence.Using LoopFirst split the sentence into words using split() and then uses a loop (for loop) to iterate through the words and keeps track of the longest word by comparing their lengths.Pythons = "I am learning Pyt
1 min read
Python program to find the smallest word in a sentence
Given a string S of lowercase English alphabets, the task is to print the smallest word in the given string. Examples: Input: S = âsky is blueâOutput: "is"Explanation: Length of âskyâ is 3.Length of is âisâ 2.Length of âblueâ is 4.Therefore, the smallest word is âisâ. Input: S = âgeeks for geeksâOut
5 min read
Python Program To Check String Is Palindrome Using Stack
A palindrome is a sequence of characters that reads the same backward as forward. Checking whether a given string is a palindrome is a common programming task. In this article, we will explore how to implement a Python program to check if a string is a palindrome using a stack. Example Input: str =
3 min read
Python Program to Sort Words in Alphabetical Order
The task is to write a program that takes a list of words as input and sorts them in alphabetical order. The program should display the sorted list of words, ensuring that the sorting is case-insensitive. To sort words in alphabetical order in Python, we can use the sorted() function or the sort() m
2 min read
Split a sentence into list of words in Python
When working with text in Python, we often need to break down a sentence into individual words. This task is easy to accomplish in Python using different methods. The simplest way is by using split(), but more complex tasks can be handled with regular expressions or list comprehension. Depending on
2 min read
Python Program to Check if a String is Palindrome or Not
The task of checking if a string is a palindrome in Python involves determining whether a string reads the same forward as it does backward. For example, the string "madam" is a palindrome because it is identical when reversed, whereas "hello" is not. Using two pointer techniqueThis approach involve
3 min read
Python program to check whether the string is Symmetrical or Palindrome
The task of checking whether a string is symmetrical or palindrome in Python involves two main operations . A string is symmetrical if its first half matches the second half, considering the middle character for odd-length strings. A string is palindrome if it reads the same forward and backward.For
4 min read
Python program to check if given string is vowel Palindrome
Given a string (may contain both vowel and consonant letters), remove all consonants, then check if the resulting string is palindrome or not. Examples: Input : abcuhuvmnba Output : YES Explanation : The consonants in the string "abcuhuvmnba" are removed. Now the string becomes "auua". Input : xayzu
5 min read
Python - Sequence Assignment to Words
Given a String of words, assign an index to each word. Input : test_str = 'geeksforgeeks is best' Output : {0: 'geeksforgeeks', 1: 'is', 2: 'best'} Explanation : Index assigned to each word. Input : test_str = 'geeksforgeeks best' Output : {0: 'geeksforgeeks', 1: 'best'} Explanation : Index assigned
5 min read