Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group Consecutive Increasing Numbers in List [duplicate]

Tags:

python

How can I group together consecutive increasing integers in a list? For example, I have the following list of integers:

numbers = [0, 5, 8, 3, 4, 6, 1]

I would like to group elements together as follow:

[[0, 5, 8], [3, 4, 6], [1]]

While the next integer is more than previous, keep adding to the same nested list; ones the next integer is smaller, add nested list to main list and start again.

I have tried few different ways (while loop, for loop, enumerate and range), but cannot figure out how to make it append to the same nested list as long as next integer is larger.

result = []

while (len(numbers) - 1) != 0:
    group = []

    first = numbers.pop(0)
    second = numbers[0]

    while first < second:
        group.append(first)
        
        if first > second:
            result.append(group)
        break
like image 976
W Szum Avatar asked Apr 22 '26 01:04

W Szum


1 Answers

You could use a for loop:

numbers = [0, 5, 8, 3, 4, 6, 1]
result = [[]]
last_num = numbers[0] # last number (to check if the next number is greater or equal)
for number in numbers:
    if number < last_num:
        result.append([]) # add a new consecutive list
    result[-1].append(number) 
    last_num = number # set last_num to this number, so it can be used later
print(result)

NOTE: This doesn't use .pop(), so the numbers list stays intact. Also, one loop = O(N) time complexity!!

like image 150
Ayush Garg Avatar answered Apr 24 '26 16:04

Ayush Garg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!