Search code examples
pythonlistpython-2.7trend

Subsetting python list into positive/negative movements/trends


Sorry for creating this question but I have been stuck on this question for a while.

Basically I'm trying to take a list:

numbers=[1, 2, -1, -2, 4, 5]

And subset this list into a list of list that display positive/negative movements (or trends)

The end result is to have:

subset_list = [[1, 2], [-1, -2], [4, 5]] 

Basically I have been using nested while functions to append a positive movement to the subset, and when the condition is not met, the subset is appended to subset_list and then evaluates if there is a negative movement.

I keep getting an IndexError, and so far subset_list only contains [[1, 2]]

Here is my code:

numbers = [1,2,-1,-2,4,5]

subset = []
subset_list = []
subset.append(numbers[0])

i = 1
while i < (len(numbers)):
    if numbers[i] <= numbers[i+1]:
        subset.append(numbers[i])
        i+= 1
        while subset[-1] <= numbers[i] or numbers[i] <= numbers[i+1]:
            subset.append(numbers[i])
            i += 1
        subset_list.append(subset)
        subset = []
        i += 1
    if numbers[i] > numbers[i+1]:
        subset.append(numbers[i])
        i+= 1
        while subset[-1] <= numbers[i] or numbers[i] <= numbers[i+1]:
            subset.append(numbers[i])
            i+= 1
        subset_list.append(subset)
        subset = []
        i += 1

Thanks!

-Jake


Solution

  • This is what I came up with. It is close to what you have but a little easier to read. I avoid having to increment the index counter i as much which is probably where you went wrong.

    n= [1,2,-1,-2,4,5]
    out=[]
    i=1
    tmp=[n[0]]
    while i < len(n):
            if n[i] >= 0 and tmp[-1] >= 0:
                    tmp.append(n[i])
            elif n[i] < 0 and tmp[-1] < 0:
                    tmp.append(n[i])
            else:
                    out.append(tmp)
                    tmp = [n[i]]
            i = i + 1
    if len(tmp) > 0: # typo fix was > 1
            out.append(tmp)
    
    print(out)