List all contiguous sub-arrays

后端 未结 4 438
醉酒成梦
醉酒成梦 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: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]
    

提交回复
热议问题