python-3.xnumpysettrend

Count sets of increasing trend in a list


I have to count the number of subsets where there is an increasing trend based on user input of the list and the length of the subset.

List:[1,2,3,4,5,6,7,8,9]

k: The length of the trend.

for example...if k=3 and the data points increase for three consecutive numbers, then it is counted as one.

Here the input is the list and the length of the list and k

Example:

Input: List:{1,2,3,4,5,6}

 k=3

Output: 4. {(1,2,3),(2,3,4),(3,4,5),(4,5,6)}

Solution

  • You can use the following :

    def group_by_trend(data, k):
        return [data[i*k :min((i+1)*k, len(data))] 
                for i in range(round((len(data)+1)/k))]
    
    # test
    k = 3
    List = [1,2,3,4,5,6,7,8,9]
    
    print(group_by_trend(List, k))
    

    output:

    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]