List all contiguous sub-arrays

后端 未结 4 408
醉酒成梦
醉酒成梦 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条回答
  • 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]]
    
    0 讨论(0)
  • 2020-12-29 15:46
    def kwindow(L, k):
        for i in range(len(L)-k+1):
            yield L[i:i+k]
    
    
    def getAllWindows(L):
        for w in range(1, len(L)+1):
            yield from kwindow(L, w)
    

    Ouput:

    In [39]: for i in getAllWindows([1,2,3]): print(i)
    [1]
    [2]
    [3]
    [1, 2]
    [2, 3]
    [1, 2, 3]
    
    0 讨论(0)
  • 2020-12-29 15:58

    One line solution (I don't know what means "better way" for you)

    L = [1,2,3]
    [L[i:i+j] for i in range(0,len(L)) for j in range(1,len(L)-i+1)]
    
    L=[1,2,3,4]
    [L[i:i+j] for i in range(0,len(L)) for j in range(1,len(L)-i+1)]
    

    you get,

    [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
    
    [[1],
     [1, 2],
     [1, 2, 3],
     [1, 2, 3, 4],
     [2],
     [2, 3],
     [2, 3, 4],
     [3],
     [3, 4],
     [4]]
    
    0 讨论(0)
  • 2020-12-29 16:06

    Simplifying the Inspector's solution:

    def getAllWindows(L):
        for w in range(1, len(L)+1):
            for i in range(len(L)-w+1):
                yield L[i:i+w]
    

    And a solution using no loops at all:

    def allSubArrays(L,L2=None):
        if L2==None:
            L2 = L[:-1]
        if L==[]:
            if L2==[]:
                return []
            return allSubArrays(L2,L2[:-1])
        return [L]+allSubArrays(L[1:],L2)
    
    0 讨论(0)
提交回复
热议问题