Search code examples
pythonarraystrend

Extracting upward/downwards trends in an array


I have an array consisting of temperatures from different days. My goal is to extract the elements where the temperature is either increasing or decreasing for n number of days.

Lets say we have an array consisting of following temperatures

temp=[4,5,7,8,9,7,6,7,8,6,5,4,3,2]

If we say n=3, then if for example the temperature has increased for two days in a row but then decreases on the third day we don't want to extract that information, only consider the elements where the temperature havs increased/decreased for minimum n days in a row.

Lets say n=3, then from the temp array above, the extraction would be

increasingTemp1=[4,5,7,8,9] ( i.e temp[0:5] )
increasingTemp2=[6,7,8]     ( i.e temp[6:9] )
decreasingTemp1=[9,7,6]     ( i.e temp[4:7] )
decreasingTemp2=[8,6,5,3,2] ( i.e temp[8:]  )

is there a way of doing this?

Thanks


Solution

  • Guess this is a typical LeetCode array question. I would go through the array once and build up a subarray for each sequence of increasing/decreasing numbers. If the direction of the trend changes I would check whether the length of the subarray is at least n and then would add the subarray to the list of increasing/decreasing arrays.

    One implementation could look like this (O(n) time & memory).

    def return_arrays(arr,n):
        increasing = []
        decreasing = []
        new_arr = []
        for i,elem in enumerate(arr):
            if len(new_arr)>1:
                if new_arr[0]-new_arr[-1]>=0:
                    # Decreasing
                    if new_arr[-1]>=elem:
                        new_arr.append(elem)
                    else:
                        if len(new_arr)>=n:
                            decreasing.append(new_arr)
                        new_arr = [new_arr[-1],elem]
                else:
                    # Increasing
                    if new_arr[-1]<=elem:
                        new_arr.append(elem)
                    else:
                        if len(new_arr)>=n:
                            increasing.append(new_arr)
                        new_arr = [new_arr[-1],elem]
            else:
                new_arr.append(elem)
            if i==len(arr)-1:
                if len(new_arr)>=n:
                    if new_arr[0]-new_arr[-1]>=0:
                        decreasing.append(new_arr)
                    else:
                        increasing.append(new_arr)
        return increasing,decreasing 
    

    Applying it to your problem you get the following output:

    temp = [4,5,7,8,9,7,6,7,8,6,5,4,3,2]
    return_arrays(temp,3) # ([[4, 5, 7, 8, 9], [6, 7, 8]], [[9, 7, 6], [8, 6, 5, 4, 3, 2]])
    

    I hope this helps. You may need to create and check more test cases if you want to make sure the implementation is correct.