SARSA: Learning From the Action Actually Taken

Reinforcement LearningEasy+10 XP+10

SARSA: Learning From the Action Actually Taken

Q-learning updates toward the best action available in the next state — even if the agent has no intention of taking it. SARSA updates toward the action the agent actually took:

Q(s,a)←Q(s,a)+α[r+γQ(s′,a′)−Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha \big[ r + \gamma Q(s', a') - Q(s, a) \big]Q(s,a)←Q(s,a)+α[r+γQ(s′,a′)−Q(s,a)]

The name is the five things in that formula: state, action, reward, next state, next action.

Task: write sarsa_update(q, state, action, reward, next_state, next_action, alpha, gamma) returning the full updated Q-table, every entry rounded to 4 decimal places.

  • q is a list of rows, one per state, each holding that state's action values: q[s][a].
  • Return a new table of the same shape. Exactly one entry changes.
  • alpha is the step size, gamma the discount.
  • (state, action) and (next_state, next_action) may be the same cell. Read the target value before you overwrite anything.

Swapping a max for a plain lookup sounds trivial and changes the agent's character completely. Q-learning learns the value of the optimal policy regardless of how recklessly it explores; SARSA learns the value of the policy it is actually following, exploration mistakes included. On a cliff-edge task, Q-learning walks the optimal route along the edge and occasionally falls off, while SARSA — which has felt those falls in its own updates — learns a slower, safer path.

Examples

q = [[0.0, 0.0], [0.0, 0.0]]
state = 0
action = 1
reward = 1.0
next_state = 1
next_action = 0
alpha = 0.5
gamma = 0.9
returns [[0.0, 0.5], [0.0, 0.0]]
q = [[1.0, 2.0], [3.0, 4.0]]
state = 0
action = 0
reward = 0.0
next_state = 1
next_action = 1
alpha = 0.1
gamma = 1.0
returns [[1.3, 2.0], [3.0, 4.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