List all contiguous sub-arrays

后端 未结 4 427
醉酒成梦
醉酒成梦 2020-12-29 15:14

I have an array [1, 2, 3] of integer and I need to return all the possible combination of contiguous sub-arrays of this array.

[[1],[2],[3],[1,2],

4条回答
  •  旧时难觅i
    2020-12-29 15:45

    An itertools based approach:

    import itertools
    
    def allSubArrays(xs):
        n = len(xs)
        indices = list(range(n+1))
        for i,j in itertools.combinations(indices,2):
            yield xs[i:j]
    

    For example:

    >>> list(allSubArrays([1,2,3]))
    [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
    

提交回复
热议问题