Home > database >  I want to get only those subset which have k elements in it
I want to get only those subset which have k elements in it

Time:09-19

L=[1,2,3,4,5,6,7]
K=2

The ans i want

L=[[1,2],[2,3],[3,4][4,5],[5,6],[6,7]]

In ans there should be no subset which doesn't have k elements in it

CodePudding user response:

You can iterate a number starting from 0 to the maximum number from which at least K elements exists, then create the list of list out the items starting and ending with required indices, you can use List Comprehension to accomplish this:

>>> [L[i:i K] for i in range(len(L)-K 1)]

[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]

CodePudding user response:

You can use list comprehension

answer = [[L[j] for j in range(i, i   K)] for i in range(len(L) - K)]
  • Related