Open In App

Python – Sort Strings by Case difference

Improve
Improve
Like Article
Like
Save
Share
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.



Last Updated : 21 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads