Decompose a list of integers into lists of increasing sequences

前端 未结 6 946
北恋
北恋 2020-12-20 04:33

Assume no consecutive integers are in the list.

I\'ve tried using NumPy (np.diff) for the difference between each element, but haven\'t been able to use

6条回答
  •  难免孤独
    2020-12-20 05:34

    You can write a simple script and you don't need numpy as far as I have understood your problem statement. Try the script below. I have tested it using Python 3.6.7 and Python 2.7.15+ on my Ubuntu machine.

    def breakIntoList(inp):
        if not inp:
            return []
    
        sublist = [inp[0]]
        output = []
        for a in inp[1:]:
            if a > sublist[-1]:
                sublist.append(a)
            else:
                output.append(sublist);
                sublist = [a]
    
    
        output.append(sublist)
        return output
    
    
    
    list = [1, 4, 1, 2, 4, 3, 5, 4, 0]
    print(list)
    print(breakIntoList(list))
    

    Explanation:

    1. The script first checks if input List passed to it has one or more elements.
    2. It then initialise a sublist (variable name) to hold elements in increasing order. After that, we append input List's first element into our sublist.
    3. We iterate through the input List beginning from it's second element (Index: 1). We keep on checking if the current element in Input List is greater than last element of sublist (by sublist[-1]). If yes, we append the current element to our sublist (at the end). If not, it means we can't hold that current element in sub-List. We append the sublist to output List and clear the sublist (for holding other increasing order sublists) and add the current element to our sublist.
    4. At the end, we append the remaining sublist to the output List.

提交回复
热议问题