Command Palette

Search for a command to run...

Hectal
Phase 13: Python Internals and Performance
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

  1. Every chunk is a memoryview
  2. The chunks have lengths 3, 3 and 2
  3. The contents are right, for bytes too
  4. Writing through a chunk changes the original
  5. A size of 0 raises ValueError
  6. A negative size raises ValueError
  7. An empty buffer gives no chunks, and a size larger than the buffer gives one
  8. 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.