pythonarrayspython-3.x

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

  • 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)