'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 that with python? One way would be to have 2 loops and the array itself but there should be a better way.



Solution 1:[1]

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)

Solution 2:[2]

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 3:[3]

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]

Solution 4:[4]

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

Solution 5:[5]

I have simple solutions:

from itertools import combinations
array = [1,2,3,4]
combos = [array[start:end] for start, end in combinations(range(len(array)+1), 2)]
print(combo)

Solution 6:[6]

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*
            continue
        else:
            subli=li[i:j]
            l.append(subli)
 print(l)

output:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jose Ricardo Bustos M.
Solution 3 inspectorG4dget
Solution 4 John Coleman
Solution 5 Stuart
Solution 6