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 isalpha() + isnumeric() + zip_longest() The combination of above methods can be used to perform this task. In this, we separate the numeric and alphabets and then perform a sort on them separately and join using zip_longest().
Python3
from itertools import zip_longest
test_list = [ '3' , 'B' , '2' , 'A' , 'C' , '1' ]
print ("The original list is : " + str (test_list))
num_list = sorted ( filter ( str .isnumeric, test_list),
key = lambda sub: int (sub))
chr_list = sorted ( filter ( str .isalpha, test_list))
res = [ele for sub in zip_longest(num_list, chr_list)
for ele in sub if ele]
print (" List after performing sorting : " + str (res))
|
Output :
The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']
Method #2 : Using sorted() + key + lambda + isnumeric() The combination of above methods can be used to perform this task. In this, we perform the sorting in alternate manner using ord() and lambda function, testing using isnumeric().
Python3
from itertools import zip_longest
test_list = [ '3' , 'B' , '2' , 'A' , 'C' , '1' ]
print ("The original list is : " + str (test_list))
res = sorted (test_list, key = lambda ele : ( int (ele), 0 )
if ele.isnumeric()
else (( ord (ele) - 64 ) % 26 , 1 ))
print (" List after performing sorting : " + str (res))
|
Output :
The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']
Method #3:
- Split the list into two lists: one for digits and one for characters.
- Sort the lists using the built-in sort() function.
- Interleave the sorted lists and create the final result list.
Python3
test_list = [ '3' , 'B' , '2' , 'A' , 'C' , '1' ]
print ( "The original list is : " + str (test_list))
digits = [x for x in test_list if x.isdigit()]
chars = [x for x in test_list if x.isalpha()]
digits.sort()
chars.sort()
res = [ None ] * len (test_list)
for i in range ( len (test_list)):
if i % 2 = = 0 :
res[i] = digits[i / / 2 ]
else :
res[i] = chars[i / / 2 ]
print ( "List after performing sorting : " + str (res))
|
Output
The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']
Time complexity: O(nlogn)
Auxiliary Space:O(n)
Method #4: Using a custom sorting algorithm
- Define a function custom_sort that takes an element ele and returns a tuple (key, value) where key is a string representing the type of the element (digit or character) and value is the element itself.
- Use the sorted function to sort the list test_list using the custom_sort function as the key.
- Create two empty lists digits and chars.
- Iterate through the sorted list res and append the elements to either the digits list or the chars list, depending on their type.
- Use the zip function to combine the digits and chars lists into a single list.
- Use the itertools.chain.from_iterable function to flatten the combined list.
- Convert the flattened list back to a string using the join function.
Python3
import itertools
def custom_sort(ele):
if ele.isnumeric():
return ( 'digit' , int (ele))
else :
return ( 'char' , ele)
test_list = [ '3' , 'B' , '2' , 'A' , 'C' , '1' ]
print ( "The original list is : " + str (test_list))
res = sorted (test_list, key = custom_sort)
digits = []
chars = []
for ele in res:
if ele.isnumeric():
digits.append(ele)
else :
chars.append(ele)
combined = list ( zip (digits, chars))
result = list (itertools.chain.from_iterable(combined))
result_str = ''.join(result)
print ( "List after performing sorting : " + str (result))
|
Output
The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']
Time complexity: Sorting the list takes O(n log n) time using the sorted function, where n is the length of the list. Iterating through the sorted list takes O(n) time. Combining and flattening the lists takes O(n) time. Therefore, the overall time complexity is O(n log n).
Auxiliary space: We create two additional lists (digits and chars) and one additional tuple list (combined), each with a maximum size of n/2, where n is the length of the input list. Therefore, the auxiliary space complexity is O(n).
Last Updated :
22 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...