Python · Exercise 1 of 6Next
Intermediate
Split a buffer without copying
Write a function split_chunks(data, size) that cuts a bytes or bytearray into pieces of size bytes (the last piece may be shorter) and returns a **list of memoryview objects**, not copies.
A write through a chunk must change the original bytearray. If size is zero or negative, raise ValueError.
Then print Chunks: 3 for the buffer bytearray(b"abcdefgh") cut into pieces of 3.
What Check tests
- Every chunk is a
memoryview - The chunks have lengths 3, 3 and 2
- The contents are right, for
bytestoo - Writing through a chunk changes the original
- A size of 0 raises
ValueError - A negative size raises
ValueError - An empty buffer gives no chunks, and a size larger than the buffer gives one
- The program prints
Chunks: 3
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.