0

I would like to devise an algorithm that generates all combinations of five consecutive elements from a list of integers. For example:

Set -> [1, 2, 3, 4, 5, 6, 7]
Subset 1 -> [1, 2, 3, 4, 5]
Subset 2 -> [2, 3, 4, 5, 6]
Subset 3 -> [3, 4, 5, 6, 7]
  • 5
    These are just subsequnces of adjacent elements of size n. You can create that with a sliding window. This is evident from your example data. Is that what you are trying to achieve? – user1984 Jan 11 '22 at 20:36
  • 1
    Does this answer your question? [Rolling or sliding window iterator?](https://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator) – kaya3 Jan 12 '22 at 13:33

1 Answers1

0
  1. Get number of iterations from ( length of list - size + 1 )
  2. Create new list for each iteration.

Implementation in Python using list slicing:

lst = [1,2,3,4,5,6,7,8,9,10,11,12]
size = 5

num_iterations = len(lst) - size + 1

for i in range(0, num_iterations):
    print(lst[i:size + i])
Jake Beck
  • 13
  • 6