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 | Convert list of numerical string to list of Integers
- Python | Increasing alternate element pattern in list
- Python list | reverse()
- Python | Convert number to list of integers
- Python | Converting all strings in list to integers
- Python | Adding K to each element in a list of integers
- Python List Comprehension | Sort even-placed elements in increasing and odd-placed in decreasing order
- Python | Program to print duplicates from a list of integers
- Python | Reverse sign of each element in given list
- Python | Reverse each tuple in a list of tuples
- Python Program to Reverse a linked list
- Python | Convert a list of multiple integers into a single integer
- Python | Counting sign change in list containing Positive and Negative 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 firstname.lastname@example.org. 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.