1

I have a list in python [1, 2, 3, 4, 5, 6]. I want to generate all possible combinations of length 2, 3, 4 and 5. I have used itertools.combinations to generate the combinations but it doesn't generate continuous combinations only. For example, length 2 combinations should be only [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]. Is there any faster way to generate than the following code?

for start, end in combinations(range(len(lst)), 2):
    if end - start <= 4 and end-start >= 1:
        print(lst[start:end+1])
Delgan
  • 18,571
  • 11
  • 90
  • 141

3 Answers3

5

You don't need combinations at all. What you want looks more like a sliding window.

for i in range(2, 6):
    for j in range(len(lst) - i + 1):
        print(lst[j:j + i])
Delgan
  • 18,571
  • 11
  • 90
  • 141
1

You can loop over the list as following:

a = [1,2,3,4,5,6]
for i in range(2, len(a)):
    for j in range(len(a)-i + 1):
        print(a[j:j+i])
    print()

The trick here is that a[j:j+i] returns the list from j, up until j+i.

Putting this into a function form:

def continuous(lst, length):
     slices = []
     for j in range(len(lst)-length + 1):
         slices.append(a[j:j+length])
     return slices
Nathan
  • 3,558
  • 1
  • 18
  • 38
1

You can loop through the list in the following method

lst = [1, 2, 3, 4, 5 ,6]

def continuous(lst, length):
    result = []
    for i in range (0, len(lst)-length):
        entry = []
        for j in range (0, length):
            entry.append(lst[i+j])
        result.append(entry)
    return result

print(continuous(lst, 2))

or if you are just looking to print it line by line

def continuous(lst, length):
    for i in range (0, len(lst)-length):
        entry = []
        for j in range (0, length):
            entry.append(lst[i+j])
        print(entry)
Andreas
  • 2,455
  • 10
  • 21
  • 24