Python – Split List on next larger value
Last Updated :
10 Mar, 2023
Given a List, perform split on next larger value.
Input : test_list = [4, 2, 3, 7, 5, 1, 3, 4, 11, 2] Output : [[4, 2, 3], [7, 5, 1, 3, 4], [11, 2]] Explanation : After 4, 7 is greater, split happens at that element, and so on. Input : test_list = [4, 2, 3, 7, 5, 1, 3, 4, 1, 2] Output : [[4, 2, 3], [7, 5, 1, 3, 4, 1, 2]] Explanation : After 4, 7 is greater, split happens at that element.
Method : Using loop
In this, we iterate list and keep track of split value, if higher value than recorded value is found, new list is created from it, and split value is current value.
Python3
test_list = [ 4 , 2 , 3 , 7 , 5 , 9 , 3 , 4 , 11 , 2 ]
print ( "The original list is : " + str (test_list))
curr = test_list[ 0 ]
temp = []
res = []
for ele in test_list:
if ele > curr:
res.append(temp)
curr = ele
temp = []
temp.append(ele)
res.append(temp)
print ( "Split List : " + str (res))
|
Output
The original list is : [4, 2, 3, 7, 5, 9, 3, 4, 11, 2]
Split List : [[4, 2, 3], [7, 5], [9, 3, 4], [11, 2]]
Time Complexity: O(n*n), where n is the length of the input list.
Auxiliary Space: O(n*n) additional space of size n is created where n is the number of elements in the list “test_list”.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...