3

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
W Szum
  • 171
  • 5
  • 1
    What happens when you run your code? What do you want it to do differently? As a begginning programmer, you should develop skills to debug your code when it doesn't work correctly because it never works correctly the first time, no matter how skilled a programmer you become. To get you started, read [this article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) for tips on debugging your code. – Code-Apprentice Nov 23 '20 at 23:35
  • 2
    @Code-Apprentice. Not true. I had a three line program work correctly the first time once. I remember it clearly. Went off on a week long bender to celebrate. Never happened again of course. – Mad Physicist Nov 23 '20 at 23:36
  • @MadPhysicist I exaggerate for effect. – Code-Apprentice Nov 23 '20 at 23:39
  • @Code-Apprentice. Me too. The bender was only half a week long. Seemed longer though :) – Mad Physicist Nov 23 '20 at 23:41
  • @MadPhysicist Lesson learned: celebratory benders are cursed. Your code will never work again. – Code-Apprentice Nov 23 '20 at 23:41
  • Hint: The inner loop never changes the values of `first` and `second`, so either `first < second` will always be true (and therefore result in an infinite loop) or they will never be true, resulting in appending never appending a group of numbers. You can discover this behavior with the techniques in the link I gave above. – Code-Apprentice Nov 23 '20 at 23:44
  • I would say as a beginner try using as less as possible while/for loops in your code. and you dont need 2 loops by looking at your code you only need one for loop. – Shad0w Nov 23 '20 at 23:45
  • 1
    Yes, I agree with @Shad0w - instead of using nested loops (which gives a disgusting more than O(N) time), try to solve it with only a single loop (like I did!) – Ayush Garg Nov 23 '20 at 23:54

3 Answers3

8

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!!

Ayush Garg
  • 2,234
  • 2
  • 12
  • 28
2

If pandas are allowed, I would do this:

import pandas as pd
numbers = [0, 5, 8, 3, 4, 6, 1]
df = pd.DataFrame({'n':numbers})
[ g['n'].values.tolist() for _,g in df.groupby((df['n'].diff()<0).cumsum())]

produces

[[0, 5, 8], [3, 4, 6], [1]]
piterbarg
  • 8,089
  • 2
  • 6
  • 22
1

You can do this:

numbers = [0, 5, 8, 3, 4, 6, 1]
result = []
while len(numbers) != 0:
    secondresult = []
    for _ in range(3):
        if numbers != []:
            toappend = numbers.pop(0)
            secondresult.append(toappend)
        else:
            continue
    result.append(secondresult)
print(result)

use while and for loops. and append them to secondresult and result

ppwater
  • 2,315
  • 4
  • 15
  • 29
  • 1
    Great answer, but you missed out on your upvote because of the fact that there are two loops (more than O(N) time complexity!) – Ayush Garg Nov 24 '20 at 00:24
  • 1
    Oh, true.. well, if someone want more than O(N) time complexity then use my answer (But I'm sure no one will want that of course) – ppwater Nov 24 '20 at 00:36