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
# Python3 code to demonstrate working of
# Reorder for consecutive elements
# Using Counter() + loop + items()
from collections import Counter
# initializing list
test_list = [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
# printing original lists
print("The original list is : " + str(test_list))
# getting frequency
freqs = Counter(test_list)
res = []
# reordering basis of frequency
for val, cnt in freqs.items():
res.extend([val]*cnt)
# printing result
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
# Python3 code to demonstrate working of
# Reorder for consecutive elements
# Using Counter() + elements()
from collections import Counter
# initializing list
test_list = [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
# printing original lists
print("The original list is : " + str(test_list))
# reordering using elements()
res = list(Counter(test_list).elements())
# printing result
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
# Python3 code to demonstrate working of
# Reorder for consecutive elements
# Using dictionary comprehension + sorted()
# initializing list
test_list = [4, 7, 5, 4, 1, 4, 1, 6, 7, 5]
# printing original lists
print("The original list is : " + str(test_list))
# convert list to dictionary with frequency
freq_dict = {val: test_list.count(val) for val in test_list}
# sort dictionary based on frequency in descending order
sorted_dict = dict(sorted(freq_dict.items(), key=lambda item: item[1], reverse=True))
# create empty list to store reordered list
res = []
# iterate through sorted dictionary and append element to res as many times as its frequency
for key, value in sorted_dict.items():
res.extend([key] * value)
# print result
print("Reordered List : " + str(res))
OutputThe 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.
Similar Reads
Python | Retain K consecutive elements
Sometimes while working with data, we can have a problem in which we need to select some of the elements that occur K times consecutively. This problem can occur in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using groupby() + list comprehension This t
8 min read
Python - Remove Consecutive K element records
Sometimes, while working with Python records, we can have a problem in which we need to remove records on the basis of presence of consecutive K elements in tuple. This kind of problem is peculiar but can have applications in data domains. Let's discuss certain ways in which this task can be perform
7 min read
Python - Filter consecutive elements Tuples
Given a Tuple list, filter tuples that are made from consecutive elements, i.e diff is 1. Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 4), (6, 4, 6, 3)] Output : [(3, 4, 5, 6)] Explanation : Only 1 tuple adheres to condition. Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6,
5 min read
Python - Test Consecutive Element Matrix
Given a Matrix, test if it is made of consecutive elements. Input : test_list = [[4, 5, 6], [7], [8, 9, 10], [11, 12]] Output : True Explanation : Elements in Matrix range from 4 to 12. Input : test_list = [[4, 5, 6], [7], [8, 18, 10], [11, 12]] Output : False Explanation : Elements not consecutive
6 min read
Python - Similar Consecutive elements frequency
Sometimes, while working with Python, we can have a problem in which we have to find the occurrences of elements that are present consecutively. This problem have usage in school programming and data engineering. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop
5 min read
Python - Group Consecutive elements by Sign
Given a list group of consecutive elements on the basis of signs. Input : test_list = [5, -3, 2, 4, 6, -2, -1, -7, -9, 2, 3]Â Output : [[5], [-3], [2, 4, 6], [-2, -1, -7, -9], [2, 3]]Â Explanation : Elements inserted into new list on sign change.Input : test_list = [-2,3,4,5,6,-3] Output : [[-2], [3
3 min read
Python | Group consecutive list elements with tolerance
Sometimes, we might need to group list according to the consecutive elements in the list. But a useful variation of this can also be a case in which we need to consider a tolerance level, i.e allowing a skip value between numbers and not being exactly consecutive but a "gap" is allowed between numbe
3 min read
Python - Fill gaps in consecutive Records
Sometimes, while working with Python records, we can have a problem in which we have consecutive records, but a few missing and needs to be filled with any constant K. This kind of problem can have application in domains such as web development. Let's discuss certain ways in which we need to perform
3 min read
Python | Consecutive elements pairing in list
This process involves creating pairs of elements that appear next to each other, which can be invaluable for various applications such as data analysis, pattern recognition and algorithm development. We can achieve this using different methods in Python, such as using simple loops, list slicing, zip
3 min read
Python - Grouped Consecutive Range Indices of Elements
Given List of elements, for list of tuples, where each represents the continuity of occurrence of each element. Input : test_list = [1, 1, 5, 6, 5, 5] Output : {1: [(0, 1)], 5: [(2, 2), (4, 5)], 6: [(3, 3)]} Explanation : 5 present at 2nd idx and also in continuation in 4th and 5th index, and hence
8 min read