Given a list group of consecutive elements on the basis of signs.
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.
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]]
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.
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.