Created
March 7, 2024 13:22
-
-
Save gboeer/f89ce5a769e24ddb4db1876aca456f70 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def array_chunks(arr, chunk_size): | |
""" | |
Splits an array into chunks of up to `chunk_size` elements. | |
Args: | |
arr (list): The input array to be split into chunks. | |
chunk_size (int): The size of each chunk. The last chunk may be smaller if there are not enough elements left. | |
Returns: | |
list of lists: A list where each element is a chunk of the original array, up to `chunk_size` in length. | |
Examples: | |
>>> split_array_into_chunks([1, 2, 3, 4, 5], 2) | |
[[1, 2], [3, 4], [5]] | |
>>> split_array_into_chunks([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) | |
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] | |
>>> split_array_into_chunks([1, 2, 3, 4, 5, 6], 1) | |
[[1], [2], [3], [4], [5], [6]] | |
>>> split_array_into_chunks([1, 2, 3, 4, 5, 6], 7) | |
[[1, 2, 3, 4, 5, 6]] | |
""" | |
return [arr[i:i + chunk_size] for i in range(0, len(arr), chunk_size)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment