Python – Group each increasing and decreasing run in list
Given a list, the task is to write a Python program to group each increasing and decreasing run. This is known as a monotonous grouping. A list is monotonic if it is either monotone increasing or monotone decreasing. A list A is monotone decreasing if for all i <= j, A[i] >= A[j].
Example:
Input : test_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2]
Output : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1], [11, 12], [2]]
Explanation : 6 > 5 and then 2 is smaller than 6, hence becomes decreasing and new group is started. 2 and 9 being peak or transit elements, belong to individual groups.Input : test_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1]
Output : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1]]
Explanation : 6 > 5 and then 2 is smaller than 6, hence becomes decreasing and new group is started. 2 and 9 being peak or transit elements, belong to individual groups.
In this, every two lists each starting from 0th and 1st index are zipped, and then each element from both are compared to check run and change flag accordingly. The initial flag value is evaluated on basis of which of the first 2 elements is greater, post that flag is toggled to have appropriate run grouping.
Python3
# Python3 code to demonstrate working of# Monotonous grouping in List# Using loop + zip()# initializing listtest_list = [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2] # printing original listprint("The original list is : " + str(test_list))res = []temp = []is_up = Trueif test_list[0] > test_list[1]: is_up = Falsefor curr, nex in zip(test_list, test_list[1:]): temp.append(curr) # checking for increasing or decreasing to change list if (nex > curr and not is_up) or (nex < curr and is_up): res.append(temp) temp = [] # toggling is_up = not is_uptemp.append(nex)res.append(temp)# printing resultprint("Monotonous grouping : " + str(res)) |
The original list is : [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2] Monotonous grouping : [[5, 6], [2], [9], [7, 1], [10], [4, 2, 1], [11, 12], [2]]
Time Complexity: O(n)
Auxiliary Space: O(n)


