Sunday, April 9, 2023

Given a list of strings, write a program to write sort the list of strings on the basis of last character of each string.



Given a list of strings, write a program to write sort the list of strings on the basis of last character of each string.


Input:
L = ['ram', 'shyam', 'lakshami']

Output:
['lakshami', 'ram', 'shyam']

Python Code:

L=input().split()
Reverse_String=[]
for i in L:
  Reverse_String.append("".join(list(i)[::-1]))
New_SortedList=[]
for i in sorted(Reverse_String):
  New_SortedList.append("".join(list(i)[::-1]))
print(New_SortedList,end="")   


Explanation:
  1. L=input().split() - This line takes input from the user as a single line of space-separated strings and splits it into a list of strings. The resulting list is stored in the variable L.
  2. Reverse_String=[] - This line initializes an empty list Reverse_String that will be used to store the reversed strings.
  3. for i in L: Reverse_String.append("".join(list(i)[::-1])) - This line uses a loop to iterate through each string in the list L. For each string, it reverses the characters of the string using slicing ([::-1]), converts the reversed characters back into a string using join(), and then appends the reversed string to the Reverse_String list.
  4. New_SortedList=[] - This line initializes an empty list New_SortedList that will be used to store the sorted list of strings.
  5. for i in sorted(Reverse_String): New_SortedList.append("".join(list(i)[::-1])) - This line uses the sorted() function to sort the Reverse_String list based on the last character of each string (which is now the first character of the reversed string). For each sorted string, it reverses the characters of the string using slicing ([::-1]), converts the reversed characters back into a string using join(), and then appends the original string (not the reversed string) to the New_SortedList list.
  6. print(New_SortedList,end="") - This line prints the final sorted list of strings, with the end parameter set to an empty string to suppress the newline that is normally printed by print().

Overall, the program takes a list of strings, reverses the characters of each string, sorts the list based on the first character of the reversed string (which is the last character of the original string), and then prints the sorted list of strings.

No comments:

Post a Comment