Finding groups of increasing numbers in a list

前端 未结 8 2134
生来不讨喜
生来不讨喜 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: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]]
    

提交回复
热议问题