Python – Reorder for consecutive elements
Last Updated :
03 May, 2023
Given a List perform reordering to get similar elements in consecution.
Input : test_list = [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
Output : [4, 4, 4, 7, 7, 5, 5, 1, 1, 6]
Explanation : All similar elements are assigned to be consecutive.
Input : test_list = [4, 7, 5, 1, 4, 1, 6, 7, 5]
Output : [4, 4, 7, 7, 5, 5, 1, 1, 6]
Explanation : All similar elements are assigned to be consecutive.
Method #1 : Using Counter() + loop + items()
In this, we perform the task of computing frequency using Counter(), and loop and items() are used to reorder elements according to count, and access frequencies respectively.
Python3
from collections import Counter
test_list = [ 4 , 7 , 5 , 4 , 1 , 4 , 1 , 6 , 7 , 5 ]
print ( "The original list is : " + str (test_list))
freqs = Counter(test_list)
res = []
for val, cnt in freqs.items():
res.extend([val] * cnt)
print ( "Reordered List : " + str (res))
|
Output:
The original list is : [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
Reordered List : [4, 4, 4, 7, 7, 5, 5, 1, 1, 6]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using Counter() + elements()
In this, we perform the task of reordering the counted frequencies using elements(), providing a concise solution.
Python3
from collections import Counter
test_list = [ 4 , 7 , 5 , 4 , 1 , 4 , 1 , 6 , 7 , 5 ]
print ( "The original list is : " + str (test_list))
res = list (Counter(test_list).elements())
print ( "Reordered List : " + str (res))
|
Output:
The original list is : [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
Reordered List : [4, 4, 4, 7, 7, 5, 5, 1, 1, 6]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using dictionary comprehension + sorted()
- Convert the list into a dictionary with keys as elements and values as their frequency using dictionary comprehension.
- Use sorted() function to sort the dictionary based on frequency in descending order.
- Create an empty list ‘res’ to store the reordered list.
- Iterate through the sorted dictionary and append each element to the ‘res’ list as many times as its frequency.
- Return the reordered list.
Python3
test_list = [ 4 , 7 , 5 , 4 , 1 , 4 , 1 , 6 , 7 , 5 ]
print ( "The original list is : " + str (test_list))
freq_dict = {val: test_list.count(val) for val in test_list}
sorted_dict = dict ( sorted (freq_dict.items(), key = lambda item: item[ 1 ], reverse = True ))
res = []
for key, value in sorted_dict.items():
res.extend([key] * value)
print ( "Reordered List : " + str (res))
|
Output
The original list is : [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
Reordered List : [4, 4, 4, 7, 7, 5, 5, 1, 1, 6]
Time complexity: O(n log n), where n is the length of the list. This is because of the sorting operation performed on the dictionary.
Auxiliary space: O(n), where n is the length of the list. This is because of the dictionary and list created to store the frequency and reordered list, respectively.
Share your thoughts in the comments
Please Login to comment...