The Same Deal, Every Run

Data with PythonMedium+20 XP+20

The Same Deal, Every Run

A model learns from a small table of examples by going over all of it several times. Each full pass is called an epoch, and before every epoch the rows are put into a fresh random order, so the model never meets them in the same sequence twice running.

X holds the examples, one row of features each, and y holds their labels: y[i] is the answer for row X[i]. Two promises have to hold:

  • Rows and labels stay together. After shuffling, every row must still sit in the same position as its own label — otherwise each example is trained against somebody else's answer.
  • The whole run is repeatable. The same seed must give exactly the same sequence of orders every time the code runs.

Task: write shuffled_epochs(X, y, seed, epochs). It returns a list with one entry per epoch, and each entry is a tuple (X_epoch, y_epoch): the rows of X as a list in that epoch's order, and the labels as a list in the same order.

Follow this recipe exactly, so everyone's random numbers come out the same:

  1. Make one generator at the start: rng = random.Random(seed). It is Python's built-in cousin of np.random.default_rng(seed) — a seeded generator object with its own methods. One of them, rng.shuffle(some_list), rearranges that list in place into a random order.
  2. In each epoch, call rng.shuffle exactly once, on a brand-new list with one item per example, built in the examples' original order (the item for row 0 first, then row 1, and so on). How you use that one shuffle to put both X and y in order is up to you.
  3. Every epoch draws from that same rng, carrying on from where the previous epoch left off.

Don't change X or y themselves — the caller still needs them in their original order. If epochs is 0, return an empty list.

Use Python's random module rather than NumPy here: NumPy's generator produces a different sequence from the same seed, so its orders wouldn't match the tests.

Examples

X = [[1.0, 5.0], [2.0, 4.0], [3.0, 3.0], [4.0, 2.0]]
y = ['a', 'b', 'c', 'd']
seed = 7
epochs = 2
returns [([[4.0, 2.0], [2.0, 4.0], [1.0, 5.0], [3.0, 3.0]], ['d', 'b', 'a', 'c']), ([[2.0, 4.0], [3.0, 3.0], [4.0, 2.0], [1.0, 5.0]], ['b', 'c', 'd', 'a'])]
X = [[150, 3], [210, 8], [95, 1], [180, 6], [120, 2]]
y = ['no', 'yes', 'no', 'yes', 'no']
seed = 42
epochs = 1
returns [([[180, 6], [210, 8], [95, 1], [120, 2], [150, 3]], ['yes', 'yes', 'no', 'no', 'no'])]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run