Divides an iterable into chunks of specified size or based on a given function. Useful for batching Parameters: - iter: The input iterable to be divided into chunks. - n: An integer representing the size of each chunk. Default is 0. - fn: A function that takes the current i
(iter, n: int = 0, fn=None)
| 23 | |
| 24 | |
| 25 | def chunks(iter, n: int = 0, fn=None): |
| 26 | """ |
| 27 | Divides an iterable into chunks of specified size or based on a given function. |
| 28 | Useful for batching |
| 29 | |
| 30 | Parameters: |
| 31 | - iter: The input iterable to be divided into chunks. |
| 32 | - n: An integer representing the size of each chunk. Default is 0. |
| 33 | - fn: A function that takes the current index and the iterable as arguments and returns the size of the chunk. Default is None. |
| 34 | |
| 35 | Returns: |
| 36 | An iterator that yields chunks of the input iterable. |
| 37 | |
| 38 | Example usage: |
| 39 | ``` |
| 40 | data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| 41 | for chunk in chunks(data, 3): |
| 42 | print(chunk) |
| 43 | ``` |
| 44 | Output: |
| 45 | ``` |
| 46 | [1, 2, 3] |
| 47 | [4, 5, 6] |
| 48 | [7, 8, 9] |
| 49 | [10] |
| 50 | ``` |
| 51 | """ |
| 52 | arr = [] |
| 53 | for i, x in enumerate(iter): |
| 54 | arr.append(x) |
| 55 | if len(arr) == (fn(i, iter) if fn else n): |
| 56 | yield arr |
| 57 | arr = [] |
| 58 | |
| 59 | if arr: |
| 60 | yield arr |
| 61 | |
| 62 | |
| 63 | class MultiChoice: |
nothing calls this directly
no outgoing calls
no test coverage detected