Finding groups of increasing numbers in a list

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

    EDIT:

    Here's a code-golf solution (142 characters):

    def f(x):s=[0]+[i for i in range(1,len(x)) if x[i]!=x[i-1]+1]+[len(x)];return [x[j:k] for j,k in [s[i:i+2] for i in range(len(s)-1)] if k-j>1]
    

    Expanded version:

    def igroups(x):
        s = [0] + [i for i in range(1, len(x)) if x[i] != x[i-1] + 1] + [len(x)]
        return [x[j:k] for j, k in [s[i:i+2] for i in range(len(s)-1)] if k - j > 1]
    

    Commented version:

    def igroups(x):
        # find the boundaries where numbers are not consecutive
        boundaries = [i for i in range(1, len(x)) if x[i] != x[i-1] + 1]
        # add the start and end boundaries
        boundaries = [0] + boundaries + [len(x)]
        # take the boundaries as pairwise slices
        slices = [boundaries[i:i + 2] for i in range(len(boundaries) - 1)]
        # extract all sequences with length greater than one
        return [x[start:end] for start, end in slices if end - start > 1]
    

    Original solution:

    Not sure whether this counts as "pythonic" or "not too verbose":

    def igroups(iterable):
        items = iter(iterable)
        a, b = None, next(items, None)
        result = [b]
        while b is not None:
            a, b = b, next(items, None)
            if b is not None and a + 1 == b:
                result.append(b)
            else:
                if len(result) > 1:
                    yield tuple(result)
                result = [b]
    
    print(list(igroups([])))
    print(list(igroups([0, 0, 0])))
    print(list(igroups([7, 8, 9, 10, 6, 0, 1, 2, 3, 4, 5])))
    print(list(igroups([8, 9, 10, 11, 7, 1, 2, 3, 4, 5, 6])))
    print(list(igroups([9, 1, 2, 3, 1, 1, 2, 3, 5])))
    

    Output:

    []
    []
    [(7, 8, 9, 10), (0, 1, 2, 3, 4, 5)]
    [(8, 9, 10, 11), (1, 2, 3, 4, 5, 6)]
    [(1, 2, 3), (1, 2, 3)]
    

提交回复
热议问题