Skip to content
Related Articles

Related Articles

Python – Sort Strings by Maximum ASCII value
  • Last Updated : 11 Oct, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :