Sorted in reverse order using Python
Python’s sorted() method allows us to sort user-provided string input. But what if we need to sort the input text in reverse order? I was wondering whether the sorted() method supports reverse sorting. In a word, yes. Here, we’ll go through using the sorted() method to do a backwards sort on the supplied string.
For reversing a sorted string, use the sorted() method.
As strings in Python are immutable data types, sorting them in reverse is a challenging task. Yet, the sorted() method makes it simple to do the process of reverse sorting of strings. Here’s how to utilise sorted(inverse )’s sorting functionality.
methods:
- With the help of sorted() + reduce() + lambda
- With the help of join() + sorted() + reverse key
We will walk through an example programme for both of the aforementioned techniques to see how they are implemented.
First approach: use sorted(), reduce(), and lambda.
Using the reduction() and lambda functions in conjunction with the sorted() method allows us to invert the order of the strings. To do this, we will first apply certain inverse operations on the input text and then use the lambda function to combine the resulting list of characters in reverse order.
Please take note that this method is only compatible with Python 2.x. Specifically, if we run on Python 3.x versions, an error will be generated since the reduce() method was deleted. Example:
Results from
# Taking an input string
inputString = input("Give an input string for reverse sorting: ")
# Reverse Sorting the input string
resultantString = reduce(lambda x, y: x + y, sorted(inputString, reverse = True)) # reverse sorting with using sorted() + reduce() + lambda function
# printing reverse sorted string in output as result
print("The input string after reverse sorting is: " + str(resultantString))
Give an input string for reverse sorting: JAVATPOINT The input string after reverse sorting is: VTTPONJIAA
Second Approach: join(), sorted(), and reverse key.
The work of reverse sorting may be accomplished quickly and efficiently in only two operations by combining the join() function and the reverse key with the sorted() function. The first step is to get the list of characters in reverse order, and the second is to unite these characters to obtain the string in reverse order. Example:
result of
# Taking an input string
inputString = input("Give an input string for reverse sorting: ")
# Reverse Sorting the input string
resultantString = ''.join(sorted(inputString, reverse = True)) # reverse sorting with using sorted() + join() function with reverse key
# printing reverse sorted string in output as result
print("The input string after reverse sorting is: " + str(resultantString))
Give an input string for reverse sorting: JAVATPOINT The input string after reverse sorting is: VTTPONJIAA