Finding groups of increasing numbers in a list

前端 未结 8 2195
生来不讨喜
生来不讨喜 2021-01-05 03:37

The aim is to find groups of increasing/monotonic numbers given a list of integers. Each item in the resulting group must be of a +1 increment from the previous item

8条回答
  •  天命终不由人
    2021-01-05 04:30

    A (really) simple implementation:

    x = [7, 8, 9, 10, 6, 0, 1, 2, 3, 4, 5]
    result = []
    current = x[0]
    temp = []
    for i in xrange(1, len(x)):
        if (x[i] - current == 1):
            temp.append( x[i] )
        else:
             if (len(temp) > 1):
                 result.append(temp)
             temp = [ x[i] ]
        current = x[i]
    result.append(temp)
    

    And you will get [ [7, 8, 9, 10], [0, 1, 2, 3, 4, 5] ]. From there, you can get the number of increasing numbers by [ len(x) for x in result ] and the total number of numbers sum( len(x) for x in result).

提交回复
热议问题