Replay Buffer: Regroup a Batch by Field

Reinforcement LearningEasy+10 XP+10

Replay Buffer: Regroup a Batch by Field

A deep RL agent doesn't learn from each transition as it happens — consecutive steps are far too similar, and training on them in order makes the network chase whatever it's doing right now. Instead it stores transitions in a replay buffer and trains on scattered batches pulled back out of it.

Training code wants that batch grouped by field, not by transition: all the states together, all the actions together, and so on, because that's the shape a network consumes.

Task: write sample_batch(buffer, indices) returning [states, actions, rewards, next_states].

  • buffer is a list of transitions, each one [state, action, reward, next_state].
  • indices says which transitions to pull, in that order — the sampling has already been done for you.
  • The output is four lists, each as long as indices: all the states first, then all the actions, then the rewards, then the next states.
  • An index may appear more than once, in which case that transition appears in the batch more than once. Sampling with replacement is normal and must not be de-duplicated.
  • Keep the values exactly as stored; don't round anything.

The reshape is the whole job: you're handed data organised one transition at a time, and you have to hand back data organised one field at a time.

Examples

buffer = [[0, 1, 0.5, 1], [1, 0, -1.0, 2], [2, 1, 2.0, 3]]
indices = [2, 0]
returns [[2, 0], [1, 1], [2.0, 0.5], [3, 1]]
buffer = [[0, 0, 0.0, 0]]
indices = [0, 0, 0]
returns [[0, 0, 0], [0, 0, 0], [0.0, 0.0, 0.0], [0, 0, 0]]

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