Python program to sort Palindrome Words in a Sentence

PythonServer Side ProgrammingProgramming

When it is required to sort the palindrome words present in a sentence, a method is defined that takes a string as a parameter and first ensures that it is a palindrome. Then it sorts all the words of a string and returns it as output.

Example

Below is a demonstration of the same

def check_palindrome(my_string):
   if(my_string == my_string[::-1]):
      return True
   else:
      return False

def print_sort_palindromes(my_sentence):
   my_list = []

   my_result = list(my_sentence.split())

   for i in my_result:

      if(check_palindrome(i)):
         my_list.append(i)

   my_list.sort()

   j = 0

   for i in range(len(my_result)):

      if(check_palindrome(my_result[i])):
         my_result[i] = my_list[j]
         j = j + 1

   for i in my_result:
      print(i)

my_sentence = "hi madam, how are u"
print("The sentence is ")
print(my_sentence)
print("The result is :")
print_sort_palindromes(my_sentence)

Output

The sentence is
hi madam, how are u
The result is :
hi
madam,
how
are
u

Explanation

  • A method named ‘check_palindrome’ is defined that takes a string as a parameter.

  • It checks to see if a string is a palindrome.

  • Another method named ‘print_sort_palindromes’ is defined that takes a sentence as a parameter.

  • Inside this function, an empty list is created.

  • The sentence is split based on spaces, and converted into a list of elements.

  • The list elements are iterated over, and are checked to see the words in the sentence are palindromes.

  • If yes, it is appended to the empty list.

  • This list is sorted.

  • Outside the method, the sentence is defined and is displayed on the console.

  • The method is called by passing the parameter.

  • The output is displayed on the console.

raja
Published on 20-Sep-2021 11:45:10
Advertisements