Python - Sort Strings by Maximum ASCII value
Last Updated :
08 Feb, 2024
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))
OutputThe 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))
OutputThe original list is : ['geeksforgeeks', 'is', 'best', 'for', 'cs']
Sorted List : ['for', 'geeksforgeeks', 'is', 'cs', 'best']
Time Complexity: O(n) -> built-in functions like max takes O(n)
Auxiliary Space: O(n)
Method 3: Using heapq.nlargest():
In this approach, we can use the heapq.nlargest() function to find the n largest elements of a list based on a given key function. We can pass k=len(test_list) to get all the elements of the list, and use a lambda function to return the maximum ASCII value of each string.
Python3
import heapq
test_list = ["geeksforgeeks", "is", "best", "cs"]
sorted_list = heapq.nlargest(len(test_list), test_list, key=lambda s: max(map(ord, s)))
print(sorted_list) # Output: ['geeksforgeeks', 'is', 'cs', 'best']
Output['best', 'geeksforgeeks', 'is', 'cs']
Time Complexity: O(nmlog(k)), where n is the number of strings in the list, m is the length of the longest string, and k is the number of largest elements to be found. In this case, k is equal to len(test_list), so the time complexity is O(nmlog(n)).
Auxiliary Space: O(k), where k is the number of largest elements to be found. In this case, k is equal to len(test_list), so the space complexity is O(n).
Method #4: Using a custom function with list comprehension
Python3
# Python3 code to demonstrate working of
# Sort Strings by Maximum Character
# Using a custom function with list comprehension
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "cs"]
# defining custom function to get maximum character ASCII value
def max_char_ascii(s):
return ord(max(s))
# using list comprehension to create list of tuples
lst = [(s, max_char_ascii(s)) for s in test_list]
# sorting list of tuples based on second element (maximum character ASCII value)
res = sorted(lst, key=lambda x: x[1])
# extracting first element of each tuple (original string)
res = [t[0] for t in res]
# printing result
print("Sorted List : " + str(res))
OutputSorted List : ['for', 'geeksforgeeks', 'is', 'cs', 'best']
Time complexity: O(n log n) (due to the use of the sorted() function)
Auxiliary space: O(n) (for the lst list of tuples)
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
ASCII Values Alphabets ( A-Z, a-z & Special Character Table ) ASCII (American Standard Code for Information Interchange) is a standard character encoding used in telecommunication. The ASCII pronounced 'ask-ee', is strictly a seven-bit code based on the English alphabet. ASCII codes are used to represent alphanumeric data. The code was first published as a sta
7 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read