medium +20 pts

Cartesian Product Generator

Build a lazy generator that yields Cartesian product combinations from any number of iterables.

Write a generator function `cartesian_product(*iterables)` that yields lists representing the Cartesian product of the given iterables, in the same order as `itertools.product`. The function must be lazy: it should yield results one by one and not build a list of all combinations at once. The number of iterables is variable; if no iterables are given, the generator should yield exactly one empty list: `[]`. For each yield, the list should have one element from each input iterable, with the first iterable varying slowest and the last fastest. Implement the function yourself without importing `itertools.product`. You may use any other standard library modules if needed.

Constraints

Inputs are finite iterables (lists, strings, ranges, etc.). The total number of combinations may be huge — your function must not precompute them all. The tests will compare yielded lists in order.

Example

>>> list(cartesian_product([1, 2], ['a', 'b']))
[[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
>>> list(cartesian_product())
[[]]
>>> list(cartesian_product([1, 2, 3]))
[[1], [2], [3]]
>>> list(cartesian_product([0, 1], [2, 3], [4, 5]))
[[0, 2, 4], [0, 2, 5], [0, 3, 4], [0, 3, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5]]
20 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Convert each input iterable to a list once so you can repeatedly iterate and track indices.
Use a list of indices initialized to 0. On each yield, increment the rightmost index and carry over.
If the number of iterables is zero, yield an empty list and stop.
Avoid recursion; an iterative state-machine approach is simpler and memory-efficient.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.