Related Articles

# Python – Group each increasing and decreasing run in list

• Last Updated : 06 Jun, 2021

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], , , [7, 1], , [4, 2, 1], [11, 12], ]

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], , , [7, 1], , [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.

Example : Using loop  + zip()

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. 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 list``test_list ``=` `[``5``, ``6``, ``2``, ``9``, ``7``, ``1``, ``10``, ``4``, ``2``, ``1``, ``11``, ``12``, ``2``]``              ` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))`` ` `res ``=` `[]``temp ``=` `[]``is_up ``=` `True` `if` `test_list[``0``] > test_list[``1``]:``    ``is_up ``=` `False``for` `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_up`` ` `temp.append(nex)``res.append(temp)`` ` `# printing result``print``(``"Monotonous grouping : "` `+` `str``(res))`

Output:

The original list is : [5, 6, 2, 9, 7, 1, 10, 4, 2, 1, 11, 12, 2]

Monotonous grouping : [[5, 6], , , [7, 1], , [4, 2, 1], [11, 12], ]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up