Finding groups of increasing numbers in a list

前端 未结 8 2132
生来不讨喜
生来不讨喜 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).

    0 讨论(0)
  • 2021-01-05 04:31

    I think the most maintainable solution would be to make it simple:

    def group_by(l):
        res = [[l[0]]]
        for i in range(1, len(l)):
            if l[i-1] < l[i]:
                res[-1].append(l[i])
            else:
                res.append([l[i]])
        return res
    

    This solution does not filter out single element sequences, but it can be easily implemented. Additionally, this has O(n) complexity. And you can make it an generator as well if you want.

    By maintainable I mean code that is not an one-liner of 300 characters, with some convoluted expressions. Then maybe you would want to use Perl :). At least you will how the function behaves one year later.

    >>> x = [7, 8, 9, 10, 6, 0, 1, 2, 3, 4, 5]
    >>> print(group_by(x))
    [[7, 8, 9, 10], [6], [0, 1, 2, 3, 4, 5]]
    
    0 讨论(0)
提交回复
热议问题