Python | Alternate Sort in String list
Last Updated :
08 May, 2023
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 + sorted() This task can be achieved by using combination of functionalities above. In this, we perform the sort using just %2 elements in String list. The extension of this operation to entire list is performed by generator expression.
Python3
test_list = [ 'cdab' , 'gfeh' , 'kjil' ]
print ("The original list : " + str (test_list))
res = ["".join( sorted (j, reverse = i % 2 )) for i, j in enumerate (test_list)]
print ("The String list after alternate sorting : " + str (res))
|
Output :
The original list : ['cdab', 'gfeh', 'kjil']
The String list after alternate sorting : ['abcd', 'hgfe', 'ijkl']
Time Complexity: O(n*nlogn), where n is the length of the input list. This is because we’re using min() + generator expression which has a time complexity of O(n*nlogn) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2: Using For loop +enumerate()+sorted()+join().
Python3
test_list = [ 'cdab' , 'gfeh' , 'kjil' ]
print ( "The original list : " + str (test_list))
result = []
for i, word in enumerate (test_list):
if i % 2 = = 0 :
result.append(''.join( sorted (word)))
else :
result.append(''.join( sorted (word, reverse = True )))
print ( "The String list after alternate sorting : " + str (result))
|
Output
The original list : ['cdab', 'gfeh', 'kjil']
The String list after alternate sorting : ['abcd', 'hgfe', 'ijkl']
Time Complexity: O(m * nlogn), where m is length of test_list and n is sorting the sub strings of test_list
Auxiliary Space: O(n)
Please Login to comment...