QuantumTraveler
QuantumTraveler

Reputation: 271

Split list into even size overlapping chunks n-max

I would like to split a list into even size chunks with n-max as an argument. If n-max is greater than the list length, split the list into it's greatest overlapping chunk.

Example:

l = [1,2,3,4,5,6,7,8,9]
n-max = 4
for k, v in enumerate (l):
    if k < len(l):
        a = l[k:k+n-max]
        if len(a) == n-max:
            yield a

>>> [[1,2,3,4],[2,3,4,5],[3,4,5,6,.  [4,5,6,7],[5,6,7,8],[6,7,8,9]]

When the length of l is less than the n-max. I want it to return the maximum overlapping chunk,

l = [1,2,3]
>>> [[1,2],[2,3]]

The maximum overlapping chunk size is 2. I need the function to automatically set the decrease n-max chunk size to the possible overlapping chunk size of the list if the list cannot chunk it at the n-max.

Upvotes: 1

Views: 1091

Answers (1)

Kasravnd
Kasravnd

Reputation: 107337

As a pythonic way you can use a list comprehension for splitting your list by choosing the minimum of the n and len(your_list)-1 as the chunk size.

def chunk(n, lst):
    n = min(n, len(lst)-1)
    return [lst[i:i+n] for i in range(len(lst) - n+1)]

Demo:

In [40]: chunk(4, l)
Out[40]: 
[[1, 2, 3, 4],
 [2, 3, 4, 5],
 [3, 4, 5, 6],
 [4, 5, 6, 7],
 [5, 6, 7, 8],
 [6, 7, 8, 9]]

In [41]: l = [1,2,3,4,5,6,7,8,9,10,11]

In [42]: chunk(16, l)
Out[42]: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]

Upvotes: 3

Related Questions