easy +8 pts

Cartesian Product Pairs

Generate every ordered pair from two lists, then sort them elegantly.

Write a function `cartesian_product(a, b)` that takes two lists `a` and `b` and returns a list of all ordered pairs `(x, y)` where `x` comes from `a` and `y` comes from `b`. The result must be sorted first by the first element of the pair, and then by the second element (i.e., lexicographic order). The input lists may contain any hashable and comparable elements (e.g., ints, strings). The order of elements within each input list does not matter. Do not mutate the input lists. Return a list of lists, where each inner list has exactly two elements in the order `[x, y]`. Examples: - `cartesian_product([1,2], ['a','b'])` returns `[[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]`. - `cartesian_product([], [1,2])` returns `[]`.

Constraints

- `0 <= len(a), len(b) <= 1000` - Elements of `a` and `b` are hashable and comparable. - The output size is `len(a) * len(b)` and may be up to 1,000,000, but the function should run reasonably within memory/time limits. - Avoid using itertools.product (use loops or comprehensions) to demonstrate basic list building.

Example

>>> cartesian_product([1,2], ['a','b'])
[[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
>>> cartesian_product([], [1,2])
[]
>>> cartesian_product(['x'], [1])
[['x', 1]]
>>> cartesian_product([2,1], [0])
[[1, 0], [2, 0]]
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a nested loop: for each x in a, for each y in b, collect an ordered pair.
After building the list of pairs, sort it using the default ordering (comparison of the first element, then the second).
Empty input yields an empty list naturally from the loop condition.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.