Command Palette

Search for a command to run...

Hectal
Phase 9: Iterators, Generators and Decorators
Python · Exercise 3 of 6 PreviousNext
Intermediate

Split a stream into batches

Write a generator batches(items, size) that yields lists of up to size items taken from any iterable, in order. The last batch may be shorter. It must work lazily, even on an endless iterable. If size is less than 1, raise ValueError.

Do not use itertools.batched. Then print the batches of ["d1", "d2", "d3", "d4", "d5"] with size 2, one per line. This is how documents are grouped before they are sent to an embedding API.

What Check tests

  1. Five items in batches of 2
  2. Empty input gives no batches
  3. A size larger than the input gives one batch
  4. It accepts a one-shot iterator and a string, and an exact fit has no empty last batch
  5. It works lazily on an endless iterable
  6. A size below 1 raises ValueError
  7. The program prints the three batches

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.