Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Maximum String Value Length of Key - Python
Next article icon

Python – Sort Strings by Maximum ASCII value

Last Updated : 08 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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'] 

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))
 
 
Output
Sorted 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)



Next Article
Maximum String Value Length of Key - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • ASCII
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Sort Strings by maximum frequency character
    Given a string, the task is to write a Python program to perform sort by maximum occurring character. Input : test_list = ["geekforgeeks", "bettered", "for", "geeks"] Output : ['for', 'geeks', 'bettered', 'geekforgeeks'] Explanation : 1 < 2 < 3 < 4, is ordering of maximum character occurren
    3 min read
  • Maximum String Value Length of Key - Python
    The task of finding the maximum string length of a specific key in a list of dictionaries involves identifying the longest string associated with the given key. Given a list of dictionaries, the goal is to extract the string values of the specified key, compute their lengths and determine the maximu
    3 min read
  • Python - Sort Matrix by Maximum String Length
    Given a matrix, perform row sort basis on the maximum length of the string in it. Input : test_list = [['gfg', 'best'], ['geeksforgeeks'], ['cs', 'rocks'], ['gfg', 'cs']] Output : [['gfg', 'cs'], ['gfg', 'best'], ['cs', 'rocks'], ['geeksforgeeks']] Explanation : 3 < 4 < 5 < 13, maximum leng
    3 min read
  • Python program to list Sort by Number value in String
    Given a List of strings, the task is to write a Python program to sort list by the number present in the Strings. If no number is present, they will be taken to the front of the list. Input : test_list = ["gfg is 4", "all no 1", "geeks over 7 seas", "and 100 planets"] Output : ['all no 1', 'gfg is 4
    6 min read
  • Convert String List to ASCII Values - Python
    We need to convert each character into its corresponding ASCII value. For example, consider the list ["Hi", "Bye"]. We want to convert it into [[72, 105], [66, 121, 101]], where each character is replaced by its ASCII value. Let's discuss multiple ways to achieve this. Using List Comprehension with
    3 min read
  • Python Program to Sort a String
    Sorting strings in Python is a common and important task, whether we need to organize letters alphabetically or systematically handle text data. In this article, we will explore different methods to sort a string starting from the most efficient to the least. Using sorted with join()sorted() functio
    2 min read
  • Sort Numeric Strings in a List - Python
    We are given a list of numeric strings and our task is to sort the list based on their numeric values rather than their lexicographical order. For example, if we have: a = ["10", "2", "30", "4"] then the expected output should be: ["2", "4", "10", "30"] because numerically, 2 < 4 < 10 < 30.
    2 min read
  • Python - Maximum Scoring word
    Given a String, the task is to write a Python program to compute maximum scoring words i.e words made of characters with a maximum positional summation. Examples: Input : test_str = 'geeks must use geeksforgeeks for cs knowledge'Output : geeksforgeeksExplanation : Sum of characters positional values
    5 min read
  • Python - Descending Sort String Numbers
    Reverse Sorting a list is easy task and has been dealt with in many situations. With Machine Learning and Data Science emerging, sometimes we can get the data in the format of list of numbers but with string as data type. Generic Sort functions give erroneous result in that case, hence several other
    3 min read
  • How to sort a list of strings in Python
    In this article, we will explore various methods to sort a list of strings in Python. The simplest approach is by using sort(). Using sort() MethodThe sort() method sorts a list in place and modifying the original list directly. [GFGTABS] Python a = ["banana", "apple", "cher
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences