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 numbers. Let’s discuss an approach in which this task can be performed.
Method 1: Using generator
The brute method to perform this task. Using a loop and generator, one can perform this task. The slicing is taken care of by the yield operator and hence this problem is solved by a small check of tolerance as well.
Python3
# Python3 code to demonstrate working of # Group consecutive list elements with tolerance # Using generator # helper generator def split_tol(test_list, tol): res = [] last = test_list[ 0 ] for ele in test_list: if ele - last > tol: yield res res = [] res.append(ele) last = ele yield res # initializing list test_list = [ 1 , 2 , 4 , 5 , 9 , 11 , 13 , 24 , 25 , 26 , 28 ] # printing original list print ( "The original list is : " + str (test_list)) # Group consecutive list elements with tolerance # Using generator res = list (split_tol(test_list, 2 )) # printing result print ( "The splitted list is : " + str (res)) |
Time Complexity: O(n)
Space Complexity: O(n)
The original list is : [1, 2, 4, 5, 9, 11, 13, 24, 25, 26, 28] The splitted list is : [[1, 2, 4, 5], [9, 11, 13], [24, 25, 26, 28]]
Method 2: Using a loop
- Initialize an empty list groups to store the groups of consecutive elements.
- Initialize a variable last to store the last element of the previous group. Set last to None initially.
- Initialize an empty list group to store the current group of consecutive elements.
- Loop through each element ele in the given list test_list.
- If last is None, set it to ele and append ele to group. This is the first element of the first group.
- Else if the difference between ele and last is less than or equal to the tolerance, append ele to group.
- This element is part of the current group.
- Else, append the current group to groups and start a new group with ele. This element is the first element of a new group.
- Set last to ele for the next iteration.
- Append the last group to groups after the loop ends.
- Return the list of groups.
Python3
def group_consecutive_with_tolerance(test_list, tol): groups = [] last = None group = [] for ele in test_list: if last is None : last = ele group.append(ele) elif ele - last < = tol: group.append(ele) else : groups.append(group) group = [ele] last = ele groups.append(group) return groups # Example usage test_list = [ 1 , 2 , 4 , 5 , 9 , 11 , 13 , 24 , 25 , 26 , 28 ] tol = 2 result = group_consecutive_with_tolerance(test_list, tol) print (result) |
[[1, 2, 4, 5], [9, 11, 13], [24, 25, 26, 28]]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.