HomeLanguagesPython – Split List on next larger value

Python – Split List on next larger value

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




# Python3 code to demonstrate working of
# Split List on next larger value
# Using loop
 
# initializing list
test_list = [4, 2, 3, 7, 5, 9, 3, 4, 11, 2]
 
# printing original list
print("The original list is : " + str(test_list))
 
# starting value as ref.
curr = test_list[0]
temp = []
res = []
for ele in test_list:
     
    # if curr value greater than split
    if ele > curr:
        res.append(temp)
        curr = ele
        temp = []
    temp.append(ele)
res.append(temp)
 
# printing results
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”. 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32548 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6922 POSTS0 COMMENTS
Nicole Veronica
12037 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12143 POSTS0 COMMENTS
Shaida Kate Naidoo
7057 POSTS0 COMMENTS
Ted Musemwa
7298 POSTS0 COMMENTS
Thapelo Manthata
7015 POSTS0 COMMENTS
Umr Jansen
7001 POSTS0 COMMENTS