Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chunking list including overlapping intervals

Given the following list:

l1 = [0,1000,5000,10000,20000,30000,40000,50000]

I know I can create chunks of it by looking at every consecutive pair of numbers:

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))

for group in chunker(l1, 2):
   print(group)

This returns:

[0, 1000]
[5000, 10000]
[20000, 30000]
[40000, 50000]

How can I make sure that overlapping intervals, such as [1000,5000], are also included?

Expected output:

[0, 1000]
[1000, 5000] 
[5000, 10000]
[10000, 20000]
[20000, 30000]
[30000, 40000]
[40000, 50000]
like image 941
Zizzipupp Avatar asked Apr 20 '26 18:04

Zizzipupp


1 Answers

You unnecessarily iterate over range with the step size. This way you prevent groups starting in place where the other group finishes. This code should work:

l1 = [0,1000,5000,10000,20000,30000,40000,50000]

def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq)))

for group in chunker(l1, 2):
   print(group)

The output is:

[0, 1000]
[1000, 5000]
[5000, 10000]
[10000, 20000]
[20000, 30000]
[30000, 40000]
[40000, 50000]
[50000]

You may skip the last element if that is what you wish, but depends on your requirement.

like image 71
Joanna Avatar answered Apr 22 '26 10:04

Joanna