List all contiguous sub-arrays

后端 未结 4 433
醉酒成梦
醉酒成梦 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 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)
    

提交回复
热议问题