This is a very common problem for a list of number = [1,2,3]
I want to generate all possible consecutive subsequence
answer ==> [1],[2],[3],[1,2],[2,3],[1,2,3]
I have tried two solutions
lst = [1,2,3,4]
n = len(lst)
for i in range(n):
for j in range(i+1, n):
print(lst[i:j])
Output =
[1]
[1, 2]
[1, 2, 3]
[2]
[2, 3]
[3]
Problem this is O(n^2)
time complexity and gives Time Limited Exceeded error most of the times what is a faster way to achieve this?
I have also tried using itertools.combinations()
import itertools
lst = [1, 2, 3]
combs = []
for i in range(1, len(lst)+1):
els = [list(x) for x in itertools.combinations(lst, i)]
combs.extend(els)
print(combs)
But it generates an extra pair (1,3) which is not consecutive and hence not required Output
[[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]