Reverse Sort a String – Python
The goal is to take a given string and arrange its characters in descending order based on their Unicode values. For example, in the string “geeksforgeeks”, the characters will be sorted from highest to lowest, resulting in a new string like “ssrokkggfeeeee”. Let’s understand different methods to perform this operation efficiently.
Using sorted() with reverse=True
This is the most straightforward way to reverse sort a string. sorted() function lets us easily sort elements and the reverse=True parameter ensures the order is descending.
s = "geeksforgeeks"
res = "".join(sorted(s, reverse=True))
print(res)
Output
ssrokkggfeeee
Explanation:
- sorted() function sorts characters of the string.
- Adding reverse=True sorts them in descending order.
- “”.join() combines the sorted characters into a single string.
Using list.sort()
If we are working with a string that has been converted into a list, we can use sort() method to reverse sort it in place. This method is slightly faster for large strings as it avoids creating a new list.
s = "geeksforgeeks"
# Convert string to list and reverse sort
a = list(s)
a.sort(reverse=True)
res = "".join(a)
print(res)
Output
ssrokkggfeeee
Explanation:
- list(s) converts the string s into a list of characters.
- a.sort(reverse=True) sorts the list a in descending order.
- “”.join(a) combines the sorted characters into a final string.
Using recursion
Recursion provides an unconventional approach to reverse sorting a string. It identifies the maximum character in the string repeatedly and appends it to the result.
def fun(s):
if len(s) <= 1: # Base case
return s
m = max(s)
s = s.replace(m, "", 1) # Remove it from the string
return m + fun(s)
s = "geeksforgeeks"
res = fun(s)
print(res)
Output
ssrokkggfeeee
Explanation:
- if len(s) <= 1 checks if the string s has one or fewer characters, in which case it’s returned as is (base case).
- m = max(s) finds the maximum character in the string s.
- return m + fun(s) recursively calls fun(s) with the modified string and adds m to the result.
Using for loop
If we want more control and prefer to manually handle the process, we can use a for loop to reverse sort a string.
s = "geeksforgeeks"
res = ""
for c in sorted(s, reverse=True):
res += c
print(res)
Output
ssrokkggfeeee
Explanation:
- sorted(s, reverse=True) sorts the string s in descending order.
- for c in sorted(s, reverse=True) iterates over each character in the sorted string.
- res += c appends each character to the result string res, which is then printed.