Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 520
Michael Avatar asked Jan 10 '17 19:01

Michael


1 Answers

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]]
like image 146
Jose Ricardo Bustos M. Avatar answered Sep 20 '22 04:09

Jose Ricardo Bustos M.