Solve a slippery gridworld with value iteration

Value iteration computes the optimal value of every state of a known MDP by repeatedly applying the Bellman optimality update. It is the base case for understanding planning, model-based RL and why discounting matters.

Write value_iteration(grid, gamma, step_cost, slip, theta) for a grid given as a list of equal-length strings:
- '.' free cell, '#' wall, 'G' goal (terminal), 'X' pit (terminal).
- Actions in this fixed order: 'U', 'D', 'L', 'R'.
- Choosing an action moves in that direction with probability 1 - slip, and in each of the two perpendicular directions with probability slip / 2 (for U or D the perpendiculars are L and R; for L or R they are U and D).
- A move into a wall or off the grid leaves the agent in place.
- Reward for a transition into cell s2: step_cost, plus 1.0 if s2 is 'G', plus -1.0 if s2 is 'X'.
- Terminal cells and walls always have value 0 and are never updated.
- Q(s, a) = sum over outcomes of p * (reward + gamma * V[s2]). V_new[s] = max over a of Q(s, a).
- Synchronous sweeps: every V_new is computed from the previous sweep's V. Start from V = 0. Stop after the first sweep where max |V_new - V| < theta, and use that V_new.
Return (V, policy). V is a (rows, cols) NumPy float array. policy is a list of strings with the best action letter for each free cell (ties: first in U, D, L, R order, using the final V), and '#', 'G', 'X' copied for the other cells.

Signaturedef value_iteration(grid, gamma, step_cost, slip, theta)

Example

grid [".G"], gamma 0.9, step_cost 0, slip 0. Moving R from (0, 0) earns 1, so V = [[1, 0]] and policy ["RG"].

Understand the idea

Value iteration finds how good each cell is when you act optimally, by repeating one update: the value of a cell is the best action's expected reward plus discounted value of where you land. Slipping adds randomness: you move as intended with probability 1 - slip and sideways (the two perpendicular directions) with slip / 2 each. Worked example: grid ['..G'], gamma 0.9, step_cost 0, slip 0. Sweep 1: the middle cell moving R enters G and earns 1, so V = [0, 1, 0]. Sweep 2: the left cell moving R lands in the middle: 0 + 0.9 * 1 = 0.9, so V = [0.9, 1, 0]. Sweep 3 changes nothing, so stop. Policy 'RRG'. Rules: reward for entering s2 = step_cost, plus 1 for G, minus 1 for X; Q(s, a) = sum of p * (reward + gamma * V_old[s2]); V_new = max over U, D, L, R; update all cells from the previous sweep; stop after the first sweep whose largest change is below theta; break policy ties in U, D, L, R order. Walls and terminals stay 0. This is the base of model-based planning.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: worked examplevalue_iteration(['.G'], 0.9, 0.0, 0.0, 1e-9)
  • Sample 2: deterministic 3x4value_iteration(_g, 0.9, -0.04, 0.0, 1e-8)