Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Differential Sort String Numbers and Alphabets

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”] 
Output : [‘G’, ‘L’, ‘1’, ‘9’, ’10’] 
Explanation : Alphabets sorted, succeeded by sorted digits. 

Method #1 : Using isnumeric() + loop

In this, we separate numeric and alphabetic characters, using isnumeric(), and then perform sort on each list, then perform join of both lists for obtaining result. Works with only 1 digit numbers string.

Python3




# Python3 code to demonstrate working of
# Differential Sort String Numbers and Alphabets
# Using isnumeric() + loop
 
# initializing list
test_list = ["1", "G", "7", "L", "9", "M", "4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
numerics = []
alphabets = []
for sub in test_list:
     
    # checking and inserting in respective container
    if sub.isnumeric():
        numerics.append(sub)
    else:
        alphabets.append(sub)
 
# attaching lists post sort
res = sorted(alphabets) + sorted(numerics)
 
# printing result
print("The Custom sorted result : " + str(res))


Output

The original list is : ['1', 'G', '7', 'L', '9', 'M', '4']
The Custom sorted result : ['G', 'L', 'M', '1', '4', '7', '9']

Method #2 : Using sorted() + isnumeric()

This is one liner way to solve this problem, it checks for numerics using isnumeric, and sorted() is used to perform sort(). Converts elements to integers and tests, can handle more than 1 digit numbers. 

Python3




# Python3 code to demonstrate working of
# Differential Sort String Numbers and Alphabets
# Using sorted() + isnumeric()
 
# initializing list
test_list = ["100", "G", "74", "L", "98", "M", "4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using int() to type convert to integer
# using sorted() to perform sort operation
res = sorted(test_list, key = lambda ele: (ele.isnumeric(), int(ele) if ele.isnumeric() else ele))
 
# printing result
print("The Custom sorted result : " + str(res))


Output

The original list is : ['100', 'G', '74', 'L', '98', 'M', '4']
The Custom sorted result : ['G', 'L', 'M', '4', '74', '98', '100']

Time Complexity: O(n*log(n))

Auxiliary Space: O(n)

Method #3 : Using isalpha()+sort()+extend() methods

Python3




# Python3 code to demonstrate working of
# Differential Sort String Numbers and Alphabets
# initializing list
test_list = ["1", "G", "7", "L", "9", "M", "4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
numerics = []
alphabets = []
for sub in test_list:
    # checking and inserting in respective container
    if sub.isalpha():
        alphabets.append(sub)
    else:
        numerics.append(sub)
 
# attaching lists post sort
alphabets.sort()
numerics.sort()
alphabets.extend(numerics)
 
# printing result
print("The Custom sorted result : " + str(alphabets))


Output

The original list is : ['1', 'G', '7', 'L', '9', 'M', '4']
The Custom sorted result : ['G', 'L', 'M', '1', '4', '7', '9']

Time Complexity : O(N)
Auxiliary Space : O(N)

Method 4: Using list comprehension +  isnumeric()

The idea is to separate the numbers and alphabets into two separate lists and then sorting them separately before concatenating them.

Below is the implementation:

Python3




# Python3 code to demonstrate working of
# Differential Sort String Numbers and Alphabets
# Using two separate lists
 
# initializing list
test_list = ["1", "G", "7", "L", "9", "M", "4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# separating numbers and alphabets
num_list = [int(x) for x in test_list if x.isnumeric()]
alpha_list = [x for x in test_list if not x.isnumeric()]
 
# sorting the lists
num_list.sort()
alpha_list.sort()
 
# concatenating the lists
res = alpha_list + [str(x) for x in num_list]
 
# printing result
print("The Custom sorted result : " + str(res))


Output

The original list is : ['1', 'G', '7', 'L', '9', 'M', '4']
The Custom sorted result : ['G', 'L', 'M', '1', '4', '7', '9']

Time complexity: O(n*log(n)) because the sorting of both lists takes O(n*log(n)) time. 
Auxiliary space: O(n) because we are creating two separate lists to store the numbers and alphabets, which can take up to n space.

Method 5 :  using a dictionary to group the numbers and alphabets and then sorting them separately before merging them.

Step-by-step approach:

Initialize an empty dictionary called “grouped”.
Loop through each element in the input list, “test_list”.
Check if the element is a number or an alphabet using “isnumeric()” function.
If the element is a number, add it to a list in the dictionary called “numbers”. If “numbers” does not exist in the dictionary, create it and add the number to it.
If the element is an alphabet, add it to a list in the dictionary called “alphabets”. If “alphabets” does not exist in the dictionary, create it and add the alphabet to it.
Sort the “numbers” and “alphabets” list separately.
Merge the sorted “numbers” and “alphabets” lists into a single list called “result”.
Print the result.

Python3




# Python3 code to demonstrate working of
# Differential Sort String Numbers and Alphabets
 
# initializing list
test_list = ["1", "G", "7", "L", "9", "M", "4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# group numbers and alphabets using a dictionary
grouped = {}
for elem in test_list:
    if elem.isnumeric():
        if "numbers" not in grouped:
            grouped["numbers"] = []
        grouped["numbers"].append(elem)
    else:
        if "alphabets" not in grouped:
            grouped["alphabets"] = []
        grouped["alphabets"].append(elem)
 
# sort numbers and alphabets separately
grouped["numbers"].sort()
grouped["alphabets"].sort()
 
# merge sorted lists
result = grouped.get("alphabets", []) + grouped.get("numbers", [])
 
# printing result
print("The Custom sorted result : " + str(result))


Output

The original list is : ['1', 'G', '7', 'L', '9', 'M', '4']
The Custom sorted result : ['G', 'L', 'M', '1', '4', '7', '9']

The time complexity of this approach is O(nlogn), where n is the length of the input list “test_list”. 

 The auxiliary space required by this approach is O(n), where n is the length of the input list “test_list”.

RELATED ARTICLES

Most Popular

Recent Comments