Python - Group Consecutive elements by Sign
Last Updated :
04 May, 2023
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, 4, 5, 6], [-3]]
Explanation : Elements inserted into new list on sign change.
Method #1: Using the loop
In this, whenever a sign(positive or negative) change occurs, a new list is initiated otherwise the elements are appended to a similar list as initialized.
Python3
# Python3 code to demonstrate working of
# Group Consecutive elements by Sign
# Using loop
# initializing list
test_list = [5, -3, 2, 4, 6, -2, -1, -7,
-9, 2, 3, 10, -3, -5, 3]
# printing original list
print("The original list is : " + str(test_list))
res = [[]]
for (idx, ele) in enumerate(test_list):
# checking for similar signs by XOR
if ele ^ test_list[idx - 1] < 0:
res.append([ele])
else:
res[-1].append(ele)
# printing result
print("Elements after sign grouping : " + str(res))
OutputThe original list is : [5, -3, 2, 4, 6, -2, -1, -7, -9, 2, 3, 10, -3, -5, 3]
Elements after sign grouping : [[5], [-3], [2, 4, 6], [-2, -1, -7, -9], [2, 3, 10], [-3, -5], [3]]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using groupby() + list comprehension
In this, we perform the task of grouping using groupby(), and list comprehension is used to perform the task of iterating through the list. The condition for the sign is injected using the lambda function.
Python3
# Python3 code to demonstrate working of
# Group Consecutive elements by Sign
# Using groupby() + list comprehension
import itertools
# initializing list
test_list = [-2, 3, 4, 5, 6, -3]
# printing original list
print("The original list is : " + str(test_list))
# grouped using groupby()
res = [list(ele) for idx, ele in itertools.groupby(test_list, lambda a: a > 0)]
# printing result
print("Elements after sign grouping : " + str(res))
OutputThe original list is : [-2, 3, 4, 5, 6, -3]
Elements after sign grouping : [[-2], [3, 4, 5, 6], [-3]]
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the built-in groupby() + list comprehension which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), where n is the length of the input list as we’re using additional space other than the input list itself.
Method 3: using the numpy library
Steps:
- Import the numpy library.
- Initialize the input list test_list.
- Convert the input list to a numpy array using the numpy.array() method.
- Create a boolean array by checking if each element in the numpy array is greater than zero using the numpy.greater() method.
- Use the numpy.split() method to split the numpy array into sub-arrays based on the boolean array created in step 4.
- Convert each sub-array to a list using the tolist() method.
- Print the result.
Python3
import numpy as np
# initializing list
test_list = [-2, 3, 4, 5, 6, -3]
# convert to numpy array
arr = np.array(test_list)
# create boolean array
bool_arr = np.greater(arr, 0)
# split array based on boolean array
res_arr = np.split(arr, np.where(bool_arr[:-1] != bool_arr[1:])[0]+1)
# convert each sub-array to a list
res = [i.tolist() for i in res_arr]
# print result
print("Elements after sign grouping : " + str(res))
OUTPUT :
Elements after sign grouping : [[-2], [3, 4, 5, 6], [-3]]
Time complexity: O(n)
Auxiliary space: O(n)
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 - 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 - 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 - 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
Python - Reorder for consecutive elements 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,
4 min read