Skip to content
Related Articles

Related Articles

Python – Sort Strings by Maximum ASCII value

View Discussion
Improve Article
Save Article
  • Last Updated : 07 Aug, 2022
View Discussion
Improve Article
Save Article

Given strings list, perform sort by Maximum Character in String. 

Input : test_list = [“geeksforgeeks”, “is”, “best”, “cs”] 
Output : [“geeksforgeeks”, “is”, “cs”, “best”] 
Explanation : s = s = s < t, sorted by maximum character.

Input : test_list = [“apple”, “is”, “fruit”] 
Output : [“apple”, “is”, “fruit”] 
Explanation : p < s < t, hence order retained after sorting by max. character. 

Method #1 : Using sort() + max()

In this, sorting is performed using sort() and max() is used to get maximum character from Strings.

Python3




# Python3 code to demonstrate working of
# Sort Strings by Maximum Character
# Using sort() + max()
 
# get maximum character fnc.
def get_max(sub):
 
    # returns maximum character
    return ord(max(sub))
 
 
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "cs"]
 
# printing original lists
print("The original list is : " + str(test_list))
 
# performing sorting
test_list.sort(key=get_max)
 
# printing result
print("Sorted List : " + str(test_list))

Output:

The original list is : [‘geeksforgeeks’, ‘is’, ‘best’, ‘for’, ‘cs’] Sorted List : [‘for’, ‘geeksforgeeks’, ‘is’, ‘cs’, ‘best’]

Method #2 : Using sorted() + lambda + max()

In this, we perform task of sorting using sorted(), lambda and max() are used to input logic of getting maximum character.

Python3




# Python3 code to demonstrate working of
# Sort Strings by Maximum Character
# Using sorted() + lambda + max()
 
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "cs"]
 
# printing original lists
print("The original list is : " + str(test_list))
 
# performing sorting using sorted()
# lambda function provides logic
res = sorted(test_list, key=lambda sub: ord(max(sub)))
 
# printing result
print("Sorted List : " + str(res))

Output:

The original list is : [‘geeksforgeeks’, ‘is’, ‘best’, ‘for’, ‘cs’] Sorted List : [‘for’, ‘geeksforgeeks’, ‘is’, ‘cs’, ‘best’]

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n) -> built-in functions like max takes O(n)

Space Complexity: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!