Skip to content Skip to sidebar Skip to footer

List All Contiguous Sub-arrays

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],[2,3],[1,2,3]] How can I handle th

Solution 1:

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]]

Solution 2:

Simplifying the Inspector's solution:

defgetAllWindows(L):
    for w inrange(1, len(L)+1):
        for i inrange(len(L)-w+1):
            yield L[i:i+w]

And a solution using no loops at all:

defallSubArrays(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)

Solution 3:

defkwindow(L, k):
    for i inrange(len(L)-k+1):
        yield L[i:i+k]


defgetAllWindows(L):
    for w inrange(1, len(L)+1):
        yieldfrom kwindow(L, w)

Ouput:

In[39]: foriingetAllWindows([1,2,3]): print(i)
[1][2][3][1, 2][2, 3][1, 2, 3]

Solution 4:

An itertools based approach:

import itertools

defallSubArrays(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]]

Solution 5:

li=[1,2,3]
l=[]
for i in range(length(li)):
    for j in range(i,len(li)+1):
        if i==j:                   *cancelling empty sublist item*
            continueelse:
            subli=li[i:j]
            l.append(subli)
 print(l)

output:

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

Post a Comment for "List All Contiguous Sub-arrays"