PIXELBANKv9.1.0
Menu

Discounted Return of a Trajectory

Problem Statement

Given the sequence of rewards an agent collected during one episode, compute the discounted return from the first time step.

Background

Reinforcement learning agents do not maximise the immediate reward, they maximise the return — the total reward accumulated from now until the end of the episode. Rewards that arrive later are worth less, and the discount factor gamma controls by how much:

Gt=Rt+1+γRt+2+γ2Rt+3+⋯=∑k=0T−t−1γkRt+k+1G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots = \sum_{k=0}^{T-t-1} \gamma^{k} R_{t+k+1}

Two special cases are worth internalising because they anchor the whole spectrum:

  • gamma = 0 makes the agent myopic: the return is exactly the next reward and nothing else matters.
  • gamma = 1 makes the agent far-sighted: every reward counts equally, and the return is the plain sum. This is only well defined for episodic tasks that actually terminate.

The recursive form G_t = R_{t+1} + gamma * G_{t+1} is the seed of every algorithm in this plan — the Bellman equations are nothing more than this identity with an expectation wrapped around it.

Your Task

Implement:

def discounted_return(rewards, gamma):
    ...
  • rewards — a list of floats, rewards[k] is the reward received at step k (i.e. Rk+1R_{k+1}).
  • gamma — the discount factor, 0.0 <= gamma <= 1.0.

Return the discounted return G0G_0 as a float.

Input / Output Format

Input is a Python list of floats and a float. Output is a single float. The grader rounds it to 4 decimal places.

Sample

print(round(discounted_return([1.0, 2.0, 3.0], 0.9), 4))

Output:

5.23

Because 1.0 + 0.92.0 + 0.813.0 = 1.0 + 1.8 + 2.43 = 5.23.

Example:

Input:
discounted_return([1.0, 2.0, 3.0], 0.9)
Output:
5.23
Reasoning:
  • The discounted return G0G_0 is calculated by summing each reward weighted by the discount factor γ\gamma raised to the power of its time step index: G0=∑k=0n−1γkRkG_0 = \sum_{k=0}^{n-1} \gamma^k R_k.
  • For the first reward R0=1.0R_0 = 1.0 at time step k=0k=0, the contribution is 0.90×1.0=1×1.0=1.00.9^0 \times 1.0 = 1 \times 1.0 = 1.0.
  • For the second reward R1=2.0R_1 = 2.0 at time step k=1k=1, the contribution is 0.91×2.0=0.9×2.0=1.80.9^1 \times 2.0 = 0.9 \times 2.0 = 1.8.
  • For the third reward R2=3.0R_2 = 3.0 at time step k=2k=2, the contribution is 0.92×3.0=0.81×3.0=2.430.9^2 \times 3.0 = 0.81 \times 3.0 = 2.43.
  • Summing these weighted contributions gives the total return: 1.0+1.8+2.43=5.231.0 + 1.8 + 2.43 = 5.23.
  • The final output is 5.23

Constraints:

  • 0 <= len(rewards) <= 1000
  • 0.0 <= gamma <= 1.0
  • Rewards may be negative.
  • An empty reward list has return 0.0.
  • Return a plain Python float; do not round inside the function.
solution.py

Test Results

0/0
Run code to see test results.
Discounted Return of a Trajectory - Easy | PixelBank