Open In App

Python – Reverse Sort a String

Last Updated : 03 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sorting has always been quite a popular utility with lots of applications everywhere, which Python language has opted for. Python in its language offers a sort function to perform this task. But due to the fact that not all the containers in Python are mutable, such as string, the sort function doesn’t work as it inplace tries to sort and immutability stops this. Let’s discuss certain ways in which a string can be sorted in a reverse way.

Method #1: join() + sorted() + reverse key: The combination of the above functions can potentially solve this particular problem. This task is performed in 2 steps in which the first step we get the reverse sorted list of characters and then we join the result to get the resultant sorted string. 

Python3




# Python3 code to demonstrate
# Reverse Sort a String
# using join() + sorted() + reverse
 
# initializing string
test_string = "geekforgeeks"
 
# printing original string
print("The original string : " + str(test_string))
 
# using join() + sorted() + reverse
# Sorting a string
res = ''.join(sorted(test_string, reverse = True))
     
# print result
print("String after reverse sorting : " + str(res))


Output

The original string : geekforgeeks
String after reverse sorting : srokkggfeeee

Time Complexity: O(n*logn)
Auxiliary Space: O(n), where n is the number of characters in string.

Method #2: Using sorted() + reduce() + lambda: This particular task can also be performed using the combination of 3 functions. Here we join the resultant reverse sorted list of characters using the lambda function joined by the reduce function. Works only for Python2. 

Python




# Python code to demonstrate
# Reverse Sort a String
# using sorted() + reduce() + lambda
 
# initializing string
test_string = "geekforgeeks"
 
# printing original string
print("The original string : " + str(test_string))
 
# using sorted() + reduce() + lambda
# Reverse Sort a String
res = reduce(lambda x, y: x + y, sorted(test_string, reverse = True))
     
# print result
print("String after reverse sorting : " + str(res))


Output

The original string : geekforgeeks
String after reverse sorting : srokkggfeeee

Method #3: Using list() + sort() + join(): This problem can also be solve using the combination of above 3 methods. Here we convert the string to a list and sort this list with the sort function of the list in reverse order and after that join the result into a string.

Python3




# Python code to demonstrate
# To Sort and Reverse a String
# using list() + sort() + join()
 
# initializing string
test_string = "geekforgeeks"
 
# printing original string
print("The original string : " + str(test_string))
 
# using list() + sort() + join
# To Sort and reverse a String
temp = list(test_string)
temp.sort(reverse = True)
res = "".join(temp)
     
# print result
print("String after reverse sorting : " + res)


Output

The original string : geekforgeeks
String after reverse sorting : srokkggfeeee

Time Complexity: O(nlogn)
Auxiliary space: O(n)

Method #4: Using map() function and lambda expression

Step-by-step algorithm:

  1. Initialize the list with elements containing the substring to be replaced.
  2. Print the original list.
  3. Use the map() function with lambda expression to replace the substring in each element of the list.
  4. Convert the map object to list and store it in a variable.
  5. Print the modified list.

Python3




# initializing list
test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks']
 
# print original list
print("Original List : ", test_list)
 
# replace substring using map() function and lambda expression
res = list(map(lambda x: x.replace('4', '1'), test_list))
 
# print modified list
print("Modified List : ", res)


Output

Original List :  ['4', 'kg', 'butter', 'for', '40', 'bucks']
Modified List :  ['1', 'kg', 'butter', 'for', '10', 'bucks']

Time complexity: The time complexity of the map() function is O(n), where n is the number of elements in the list. The time complexity of the replace() function is O(m), where m is the length of the string. Therefore, the overall time complexity of the code is O(n*m).
Auxiliary space: The space complexity of the code depends on the size of the list and the size of the substring to be replaced. The map() function returns a map object, which is converted to a list and stored in a variable. Therefore, the space complexity of the code is O(n), where n is the number of elements in the list.

Method #5: Using a loop:

Step-by-step approach:

  • Initialize the list test_list with the given values.
  • Print the original list using the print() function.
  • Loop through each element of the list using a for loop and the range() function.
  • Replace the substring ‘4’ with ‘1’ in each element of the list using the replace() method of string objects.
  • Update the original list with the modified elements using indexing.
  • Print the modified list using the print() function.

Python3




# initializing list
test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks']
 
# print original list
print("Original List : ", test_list)
 
# loop through each element and replace substring
for i in range(len(test_list)):
    test_list[i] = test_list[i].replace('4', '1')
 
# print modified list
print("Modified List : ", test_list)


Output

Original List :  ['4', 'kg', 'butter', 'for', '40', 'bucks']
Modified List :  ['1', 'kg', 'butter', 'for', '10', 'bucks']

Time complexity: O(n), where n is the length of the list, because we need to loop through each element of the list once.
Auxiliary space: O(1), because we are modifying the original list in place and not using any additional data structures.

Method #6: Using list comprehension

Use a list comprehension to iterate over the elements of the original list and replace the substring ‘4’ with ‘1’. The new list is created in one line without using a loop.

Python3




# initializing list
test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks']
 
# using list comprehension to modify the list
modified_list = [elem.replace('4', '1') for elem in test_list]
 
# printing the modified list
print("Modified List : ", modified_list)


Output

Modified List :  ['1', 'kg', 'butter', 'for', '10', 'bucks']

Time complexity: O(n), where n is the length of the list. 
Auxiliary space: O(n) as well, since a new list is created. 



Similar Reads

Python | Reverse Order Sort in String List
Sometimes, while working with Python, we can have a problem in which we need to perform the reverse sort operation in all the Strings that are present in a list. This problem can occur in general programming and web development. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + sorted() + join()
3 min read
Python | Flatten and Reverse Sort Matrix
The flattening of list of list has been discussed many times, but sometimes, in addition to flattening, it is also required to get the string in reverse sorted manner. Let’s discuss certain ways in which this can be done. Method #1: Using sorted() + reverse + list comprehension This idea is similar to flattening a list of list but in addition to it
6 min read
Python | Reverse Sort Row Matrix integration
Often during problem solving we come across to many problems where we need to reverse sort the list. But sometimes we would also want to reverse sort another list so that the elements of are automatically shifted and remain at same index as the first list even after first list get reverse sorted. Let’s discuss certain ways in which this can be done
7 min read
Python - Reverse Row sort in Lists of List
Sometimes, while working with data, we can have a problem in which we need to perform the sorting of rows of the matrix in descending order. This kind of problem has its application in the web development and Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + sort() + reverse This problem ca
6 min read
Python - Reverse sort Matrix Row by Kth Column
Sometimes, while working with data, we can have a problem in which we need to perform sorting of each row of records by some of decisive factor like score. This kind of problem is common in competitive programming and web development. Lets discuss certain ways in which this task can be performed. Method #1 : Using sorted() + lambda + reverse The co
4 min read
Python - Sort on basis of reverse Strings
Given a String list, sort list on basis of reverse of strings. Input : test_list = ["gfg", "is", "best", "geeks"] Output : ['gfg', 'is', 'geeks', 'best'] Explanation : g < is < ks < t [elements from rear], hence the order. Input : test_list = ["gfg", "is", "best"] Output : ['gfg', 'is', 'best'] Explanation : g < s < t [elements from
5 min read
Python Program for Odd-Even Sort / Brick Sort
This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even i
2 min read
Sort a list in Python without sort Function
Python Lists are a type of data structure that is mutable in nature. This means that we can modify the elements in the list. We can sort a list in Python using the inbuilt list sort() function. But in this article, we will learn how we can sort a list in a particular order without using the list sort() method. Sort a List Without Using Sort Functio
3 min read
Sort a Dictionary Without Using Sort Function in Python
As we all know Dictionaries in Python are unordered by default, which means they can’t be sorted directly. However, we can sort the keys or values of a dictionary and create a new sorted dictionary from the sorted keys or values. We can sort a list in a Dictionary using the inbuilt dictionary sort() function. But in this article, we will learn how
3 min read
Python | Sort each String in String list
Sometimes, while working with Python, we can have a problem in which we need to perform the sort operation in all the Strings that are present in a list. This problem can occur in general programming and web development. Let's discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + sorted() + join() This is
4 min read