diff --git a/snippets/chunk_into_n.md b/snippets/chunk_into_n.md new file mode 100644 index 000000000..2b5945555 --- /dev/null +++ b/snippets/chunk_into_n.md @@ -0,0 +1,26 @@ +--- +title: chunk_into_n +tags: list,intermediate +--- + +Chunks a list into `n` smaller lists. + +- Use `math.ceil()` and `len()` to get the size of each chunk. +- Use `list()` and `range()` to create a new list of size `n`. +- Use `map()` to map each element of the new list to a chunk the length of `size`. +- If the original list can't be split evenly, the final chunk will contain the remaining elements. + +```py +from math import ceil + +def chunk_into_n(lst, n): + size = ceil(len(lst) / n) + return list( + map(lambda x: lst[x * size:x * size + size], + list(range(0, n))) + ) +``` + +```py +chunk_into_n([1, 2, 3, 4, 5, 6, 7], 4)) # [[1, 2], [3, 4], [5, 6], [7]] +``` diff --git a/snippets/split_list.md b/snippets/split_list.md deleted file mode 100644 index c5773798b..000000000 --- a/snippets/split_list.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: split_list -tags: list,divmod,intermediate ---- - -Splits a long list into "`parts`" number of smaller lists, which are as close as possible to each other in length. - -- Check if `parts` is larger than `len(lst)` in order to not split the list into more parts than there are elements. -- The `max(len(lst), 1)` check will handle zero length lists, but `parts < 1` will yield bad results. -- `k = len(lst)//n` -> an integer specifying the number of elements in each shorter list (i.e. the quotient). -- `m = len(lst)%n` -> if `len(lst)/n` does not equal a whole number, this equals how many "extra" elements there are (i.e. the remainder). -- In order to get `n` short lists, every loop iteration goes to `i * k` and then take the next `k` elements. -- If `m > 0`, then the early iterations will have one extra element in their list until `i > m` (no extra elements left). -- Return a meta-list containing all these shorter lists. - -```py -def split_list(lst: list, parts: int) -> list: - n = min(parts, max(len(lst), 1)) - k, m = divmod(len(lst), n) - return [lst[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)] -``` - -```py -l = [1, 2, 3, 4, 5, 6] - -split_list(l, 2) # [[1, 2, 3], [4, 5, 6]] -split_list(l, 4) # [[1, 2], [3, 4], [5], [6]] -split_list(l, 9) # [[1], [2], [3], [4], [5], [6]] -```