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:
Python - Sort Strings by maximum frequency character
Next article icon

Python - Sort Strings by Case difference

Last Updated : 21 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given Strings List, the task is to write a Python program to perform sort on basis of difference of cases i.e count of lower case and upper case.

Examples:

Input : test_list = ["GFG", "GeeKs", "best", "FOr", "alL", "GEEKS"] 
Output : ['GeeKs', 'FOr', 'alL', 'GFG', 'best', 'GEEKS'] 
Explanation : ees(3) - GK(2) = 1, hence at 1st index, others are ordered accordingly.
 

Input : test_list = ["GFG", "GeeKs", "best"] 
Output : ['GeeKs', 'GFG', 'best'] 
Explanation : ees(3) - GK(2) = 1, hence at 1st index, others are ordered accordingly. 

Method #1 : Using sort() + islower() + isupper() + abs()

In this inplace sorting is performed using sort(), and islower() and isupper() is used to check for cases and count. Then abs() is used to get the absolute difference for providing parameters to perform sort over.

Python3
# Python3 code to demonstrate working of # Sort Strings by Case difference # Using sort() + islower() + isupper() + abs()   def get_case_diff(string):      # getting case count and difference     lower_cnt = len([ele for ele in string if ele.islower()])     upper_cnt = len([ele for ele in string if ele.isupper()])     return abs(lower_cnt - upper_cnt)   # initializing Matrix test_list = ["GFG", "GeeKs", "best", "FOr", "alL", "GEEKS"]  # printing original list print("The original list is : " + str(test_list))  # inplace sort using sort() test_list.sort(key=get_case_diff)  # printing result print("Sorted Strings by case difference : " + str(test_list)) 

Output:

The original list is : ['GFG', 'GeeKs', 'best', 'FOr', 'alL', 'GEEKS'] Sorted Strings by case difference : ['GeeKs', 'FOr', 'alL', 'GFG', 'best', 'GEEKS']

Time Complexity: O(nlogn)
Auxiliary Space: O(1)

Method #2 : Using sorted() + lambda + islower() + len() + isupper() + abs()

Similar to above method, difference being way of sorting used, sorted() and lambda used as a way of injecting functionality.

Python3
# Python3 code to demonstrate working of # Python3 code to demonstrate working of # Sort Strings by Case difference # Using sorted() + lambda + islower() + len() + isupper() + abs()  # initializing Matrix test_list = ["GFG", "GeeKs", "best", "FOr", "alL", "GEEKS"]              # printing original list print("The original list is : " + str(test_list))  # sorting using sorted() # lambda function to inject functionality res = sorted(test_list, key = lambda string : \         abs(len([ele for ele in string if ele.islower()]) - \         len([ele for ele in string if ele.isupper()])))  # printing result print("Sorted Strings by case difference : " + str(res)) 

Output:

The original list is : ['GFG', 'GeeKs', 'best', 'FOr', 'alL', 'GEEKS'] Sorted Strings by case difference : ['GeeKs', 'FOr', 'alL', 'GFG', 'best', 'GEEKS']

The time and space complexity for all the methods are the same:

Time Complexity: O(n*logn)

Space Complexity: O(n)

Method #3 :  Using sum + lambda

Here, we've created a get_case_difference function which takes a string as an argument and returns the absolute difference of count of lower case characters and upper case characters. In the sorted function, we pass test_list as the list to be sorted and the key argument is set to the get_case_difference function applied to each string in the list using lambda function.

Python3
def get_case_difference(string):     return abs(sum(1 for c in string if c.islower()) - sum(1 for c in string if c.isupper()))  test_list = ["GFG", "GeeKs", "best", "FOr", "alL", "GEEKS"] print("The original list is : ", test_list)  # Using map function to calculate case difference result = sorted(test_list, key=lambda x: get_case_difference(x))  # Printing result print("Sorted Strings by case difference : ", result) 

Output
The original list is :  ['GFG', 'GeeKs', 'best', 'FOr', 'alL', 'GEEKS'] Sorted Strings by case difference :  ['GeeKs', 'FOr', 'alL', 'GFG', 'best', 'GEEKS']

Time complexity: O(n log n)

Auxiliary Space: O(n)

Method #4: Using reduce():

Algorithm:

  1. Define a function get_case_difference that takes a string as input and returns the absolute value of the difference between the number of lowercase and uppercase letters in the string.
  2. Initialize a list of strings test_list.
  3. Print the original list test_list.
  4. Sort the list test_list based on the case difference of each string using the sorted function and a lambda function that calls the get_case_difference function for each string in the list.
  5. Print the sorted list of strings.
Python3
from functools import reduce  def get_case_difference(string):     return abs(reduce(lambda count, c: count + (1 if c.islower() else -1 if c.isupper() else 0), string, 0))  test_list = ["GFG", "GeeKs", "best", "FOr", "alL", "GEEKS"] print("The original list is : ", test_list)  # Using map function to calculate case difference result = sorted(test_list, key=lambda x: get_case_difference(x))  # Printing result print("Sorted Strings by case difference : ", result) #This code is contributed by Pushpa. 

Output
The original list is :  ['GFG', 'GeeKs', 'best', 'FOr', 'alL', 'GEEKS'] Sorted Strings by case difference :  ['GeeKs', 'FOr', 'alL', 'GFG', 'best', 'GEEKS']

Time Complexity:

The get_case_difference function runs in O(n) time, where n is the length of the input string.
The sorted function runs in O(n log n) time, where n is the length of the input list.
Overall, the time complexity of the code is O(n log n) since the sorted function dominates the time complexity.
Space Complexity:

The space complexity of the code is O(n), where n is the length of the input list test_list. This is because we are initializing a list of strings and storing them in memory, which takes up O(n) space. The other variables used in the code have constant space complexity.

Method #5: Using Bubble Sort Algorithm

  1. Start with the given list of strings, test_list.
  2. Set the boolean variable swapped to True to indicate that a swap has been made.
  3. Set a variable n to the length of test_list minus 1.
  4. While swapped is True:
    a. Set swapped to False.
    b. Loop through the range of n:
    i. If the absolute difference in the number of lowercase and uppercase letters in the current string is greater than the absolute difference in the number of lowercase and uppercase letters in the next string:
    1. Swap the current string and the next string.
    2. Set swapped to True.
    c. Decrement n by 1.
  5. Return the sorted list.
Python3
# Python3 code to demonstrate working of # Sort Strings by Case difference # Using Bubble Sort Algorithm  # initializing Matrix test_list = ["GFG", "GeeKs", "best", "FOr", "alL", "GEEKS"]  # printing original list print("The original list is : " + str(test_list))  # sorting using Bubble Sort Algorithm n = len(test_list) swapped = True while swapped:     swapped = False     for i in range(n - 1):         if abs(len([ele for ele in test_list[i] if ele.islower()]) - \                len([ele for ele in test_list[i] if ele.isupper()])) > \                abs(len([ele for ele in test_list[i+1] if ele.islower()]) - \                len([ele for ele in test_list[i+1] if ele.isupper()])):             test_list[i], test_list[i+1] = test_list[i+1], test_list[i]             swapped = True     n -= 1  # printing result print("Sorted Strings by case difference : " + str(test_list)) 

Output
The original list is : ['GFG', 'GeeKs', 'best', 'FOr', 'alL', 'GEEKS'] Sorted Strings by case difference : ['GeeKs', 'FOr', 'alL', 'GFG', 'best', 'GEEKS'] 

Time Complexity: O(n^2), where n is the number of strings in test_list.
Auxiliary Space: O(1), because bubble sort is an in-place sorting algorithm that does not require any additional memory allocation.


Next Article
Python - Sort Strings by maximum frequency character
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • 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
  • Python - Filter Similar Case Strings
    Given the Strings list, the task is to write a Python program to filter all the strings which have a similar case, either upper or lower. Examples: Input : test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"] Output : ['GFG', 'best', 'all', 'GEEKS'] Explanation : GFG is all uppercase, best is
    9 min read
  • Python - Sort String list by K character frequency
    Given String list, perform sort operation on basis of frequency of particular character. Input : test_list = ["geekforgeekss", "is", "bessst", "for", "geeks"], K = 's' Output : ['bessst', 'geekforgeekss', 'geeks', 'is', 'for'] Explanation : bessst has 3 occurrence, geeksforgeekss has 3, and so on. I
    4 min read
  • Python - Sort Dictionary by Value Difference
    Sometimes, while working with Python dictionaries, we can have problem in which in which we need to perform sorting of items on basis of various factors. One such can be on basis of absolute difference of dual value list. This can occur in Python > 3.6, as dictionaries are ordered. This kind of p
    3 min read
  • Python - Sort by Rear Character in Strings List
    Given a String list, perform sort by the rear character in the Strings list. Input : test_list = ['gfg', 'is', 'for', 'geeks'] Output : ['gfg', 'for', 'is', 'geeks'] Explanation : g < r < s = s, hence the order. Input : test_list = ['gfz', 'is', 'for', 'geeks'] Output : ['for', 'is', 'geeks',
    6 min read
  • Python - Differential Sort String Numbers and Alphabets
    Given a List String, Reorder List, with Sorted Alphabets followed by Sorted Strings. Input : test_list = ["1", "G", "10", "L", "9", "K", "4"] Output : ['G', 'K', 'L', '1', '4', '9', '10'] Explanation : Alphabets sorted, succeeded by sorted digits. Input : test_list = ["1", "G", "10", "L", "9"] Outpu
    5 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 - Extract Sorted Strings
    Given a String List, extract all sorted strings. Input : test_list = ["hint", "geeks", "fins", "Gfg"] Output : ['hint', 'fins', 'Gfg'] Explanation : Strings in increasing order of characters are extracted.Input : test_list = ["hint", "geeks", "Gfg"] Output : ['hint', 'Gfg'] Explanation : Strings in
    5 min read
  • Python | Sort list of dates given as strings
    To sort a list of dates given as strings in Python, we can convert the date strings to datetime objects for accurate comparison. Once converted, the list can be sorted using Python's built-in sorted() or list.sort() functions. This ensures the dates are sorted chronologically. Using pandas.to_dateti
    3 min read
  • Python - Sort String by Custom Integer Substrings
    Given a list of strings, sort strings by the occurrence of substring from list. Input : test_list = ["Good at 4", "Wake at 7", "Work till 6", "Sleep at 11"], subord_list = ["11", "7", "4", "6"] Output : ['Sleep at 11', 'Wake at 7', 'Good at 4', 'Work till 6'] Explanation : Strings sorted by substrin
    5 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