PIXELBANKv9.1.0
Menu

Problem Statement

Given a full episode of rewards R_1..R_T and bootstrap value estimates V(s_0)..V(s_T) (length T+1), compute two prediction targets for time 0.

n-step return: G0(n)=∑k=0n−1γkRk+1+γnV(sn)G^{(n)}_0 = \sum_{k=0}^{n-1} \gamma^{k} R_{k+1} + \gamma^{n} V(s_n) (if n >= T, use the full Monte-Carlo return with no bootstrap, i.e. gamma^T * V(s_T) added where V(s_T)=0 for a terminal state — but here just apply the formula with V(s_n), and if n >= T set the bootstrap term to gamma^T * values[T]).

lambda return (offline, full episode): G0λ=(1−λ)∑n=1T−1λn−1G0(n)+λT−1G0(T)G^{\lambda}_0 = (1-\lambda)\sum_{n=1}^{T-1}\lambda^{n-1} G^{(n)}_0 + \lambda^{T-1} G^{(T)}_0

Implement n_step_and_lambda(rewards, values, gamma, lam, n) returning the tuple (g_n, g_lambda). rewards has length T, values has length T+1.

Example:

Input:
n_step_and_lambda([1.0, 1.0], [0.0, 0.0, 0.0], 1.0, 0.5, 1)
Output:
(1.0, 1.5)
Reasoning:
  • Compute the 1-step return (G0(1)G^{(1)}_0): With n=1n=1, we sum the first reward discounted by γ0\gamma^0 and add the bootstrap term γ1V(s1)\gamma^1 V(s_1). Using the inputs R1=1.0R_1=1.0, γ=1.0\gamma=1.0, and V(s1)=0.0V(s_1)=0.0, the calculation is 1.0×1.0+1.0×0.0=1.01.0 \times 1.0 + 1.0 \times 0.0 = 1.0. This is the first element of the output tuple.
  • Compute the 2-step return (G0(2)G^{(2)}_0): Since the episode length T=2T=2, the 2-step return uses the full horizon. We sum both rewards (R1R_1 and R2R_2) and add the bootstrap term γ2V(s2)\gamma^2 V(s_2). The calculation is (1.0×1.0)+(1.0×1.0)+(1.0×0.0)=2.0(1.0 \times 1.0) + (1.0 \times 1.0) + (1.0 \times 0.0) = 2.0.
  • Calculate the λ\lambda-return (G0λG^{\lambda}_0): The formula combines the 1-step and 2-step returns using λ=0.5\lambda=0.5. It is computed as (1−λ)G0(1)+λT−1G0(T)(1-\lambda)G^{(1)}_0 + \lambda^{T-1}G^{(T)}_0. Substituting the values: (1−0.5)×1.0+0.52−1×2.0(1 - 0.5) \times 1.0 + 0.5^{2-1} \times 2.0.
  • Finalize the λ\lambda-return value: Evaluating the expression from the previous step: 0.5×1.0+0.5×2.0=0.5+1.0=1.50.5 \times 1.0 + 0.5 \times 2.0 = 0.5 + 1.0 = 1.5. This is the second element of the output tuple.
  • The final output is (1.0, 1.5)

Constraints:

  • len(values) == len(rewards) + 1.
  • Clamp n to at most T for the n-step term.
  • Return a tuple (g_n, g_lambda) of floats.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
n-step and Lambda Returns - Hard | PixelBank