Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
O'REILLY - "Chunk" (One-line version) solution in Speedy category for Chunk by jsg-inet
from typing import Iterable
def chunking_by(items: list, size: int) -> Iterable:
# Several lines version
# output_list=[]
# for x in range(0,len(items),size):
# output_list.append(list(items[x:x+size]))
# return output_list
# One-line version
return [items[x:x+size] for x in range(0,len(items),size)]
if __name__ == '__main__':
print("Example:")
print(list(chunking_by([5, 4, 7, 3, 4, 5, 4], 3)))
# These "asserts" are used for self-checking and not for an auto-testing
assert list(chunking_by([5, 4, 7, 3, 4, 5, 4], 3)) == [[5, 4, 7], [3, 4, 5], [4]]
assert list(chunking_by([3, 4, 5], 1)) == [[3], [4], [5]]
assert list(chunking_by([5, 4], 7)) == [[5, 4]]
assert list(chunking_by([], 3)) == []
assert list(chunking_by([4, 4, 4, 4], 4)) == [[4, 4, 4, 4]]
print("Coding complete? Click 'Check' to earn cool rewards!")
June 22, 2021
Comments: