Given a list of integers, write a Python program to reverse the order of consecutively incrementing chunk in given list.
Input : [0, 1, 9, 8, 7, 5, 3, 14] Output : [9, 1, 0, 8, 7, 5, 14, 3] Explanation: There are two chunks of strictly increasing elements (0, 1, 9) and (3, 14). Input : [-5, -3, 0, 1, 3, 5, -2, -12] Output : [5, 3, 1, 0, -3, -5, -2, -12] Explanation: Only one chunk of strictly increasing elements exists i.e. (-5, -3, 0, 1, 3, 5).
Approach #1 : Naive (Using extended slices)
A naive approach to solve the given problem is to use extended slice. We initialize two variables ‘res’ (to store final output) and block( to store chunks of incrementing integers) with empty lists. Now using a for loop, every time we check if the current element is less than the last element of block or not. If yes, add reversed chunk to ‘res’ using extended slicing (block[::-1]) and clean block (block[:] = [i]). otherwise, simply append the element to ‘block’. At last, extend ‘res’ by reversing block and output it.
[9, 1, 0, 8, 7, 5, 14, 3]
Approach #2 : Using list comprehension
An efficient approach to the above problem is to use list comprehension. It first finds out all the positions where the incrementing integers begin and stores them in a variable ‘break_’. After this, all the chunks are reversed and are managed in the form of sublists, which are in turn stored in ‘block’. Finally, ‘block’ is unzipped and returned.
[9, 1, 0, 8, 7, 5, 14, 3]
- Python | Check if list is strictly increasing
- Python | Find groups of strictly increasing numbers in a list
- Python - Test for strictly decreasing list
- Python | Convert list of numerical string to list of Integers
- Python | Increasing alternate element pattern in list
- Python list | reverse()
- Python List Comprehension | Sort even-placed elements in increasing and odd-placed in decreasing order
- Python | Converting all strings in list to integers
- Python | Adding K to each element in a list of integers
- Python | Convert number to list of integers
- Python | Summation of integers in heterogenous list
- Python | Reverse each tuple in a list of tuples
- Python | Reverse sign of each element in given list
- Python Program to Reverse a linked list
- Python | Program to print duplicates from a list of integers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.