Python - Differential Sort String Numbers and Alphabets
Last Updated :
23 Apr, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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".
Similar Reads
Separate Alphabets and Numbers in a String - Python
The task is to separate alphabets and numbers from a string. For example, given "a1b2c3", the output should be alphabets "abc" and numbers "123".Using List ComprehensionList comprehension offers a concise and efficient way to separate alphabets and numbers from a string. It iterates through each cha
2 min read
Python - Add space between Numbers and Alphabets in String
In this article, we delve into a practical Python solution to improve text readability by adding spaces between numbers and alphabets in strings by utilizing Python's powerful string manipulation capabilities. Input: test_str = 'ge3eks4geeks is1for10geeks' Output: ge 3 eks 4 geeks is 1 for 10 geeks
9 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
2 min read
Python - Sort Strings by Case difference
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
6 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 - Find Words with both alphabets and numbers
Sometimes, while working with Python strings, we can have problem in which we need to extract certain words with contain both numbers and alphabets. This kind of problem can occur in many domains like school programming and web-development. Lets discuss certain ways in which this task can be perform
6 min read
Python | Sort alternate numeric and alphabet list
Sometimes, while performing sorting in list, we have a problem in which we need to perform particular type of sorting in which we need to sort in alternate ways in which we have numerics and alphabets sorted in order. Lets discuss certain ways in which this task can be performed. Method #1 : Using i
5 min read
Python Program to test if the String only Numbers and Alphabets
Given a String, our task is to write a Python program to check if string contains both numbers and alphabets, not either nor punctuations. Examples: Input : test_str = 'Geeks4Geeks' Output : True Explanation : Contains both number and alphabets. Input : test_str = 'GeeksforGeeks' Output : False Expl
4 min read
Python | Ways to sort letters of string alphabetically
Given a string of letters, write a python program to sort the given string in an alphabetical order. Example: Input : PYTHON Output : HNOPTY Input : Geeks Output : eeGksNaive Method to sort letters of string alphabetically Here we are converting the string into list and then finally sorting the enti
2 min read
Python | Alternate Sort in String list
Sometimes, while working with Python list, we can have a problem in which we need to perform sorting only of alternatively in list. This kind of application can come many times. Let's discuss certain way in which this task can be performed. Method : Using join() + enumerate() + generator expression
2 min read