Discounted Returns, Built Backwards From the End

Reinforcement LearningEasy+10 XP+10

Discounted Returns, Built Backwards From the End

An agent collects a reward at every step. The return from a step is everything it will collect from that point to the end of the episode — but with later rewards counting for less, discounted by gamma once per step of delay:

Gt=rt+γrt+1+γ2rt+2+…G_t = r_t + \gamma r_{t+1} + \gamma^2 r_{t+2} + \dotsGt​=rt​+γrt+1​+γ2rt+2​+…

Task: write discounted_returns(rewards, gamma) returning the return for every step, in the same order as the rewards, each rounded to 4 decimal places.

  • rewards[t] is the reward collected at step t. Rewards can be negative.
  • The last step's return is just its own reward — there's nothing after it.
  • gamma runs from 0 to 1. At gamma = 0 the agent is entirely short-sighted and each return is simply that step's own reward; at gamma = 1 nothing is discounted and every return is the plain sum of what's left.

The efficient way is to walk the list backwards, carrying a running total:

Gt=rt+γ Gt+1G_t = r_t + \gamma \, G_{t+1}Gt​=rt​+γGt+1​

Start with 0 and each step needs one multiply and one add — no powers of gamma anywhere, and one pass instead of the nested loop the first formula suggests.

That rewrite is worth internalising, because it's the same move behind TD learning, GAE and every other backward recursion in reinforcement learning: a sum stretching to the horizon becomes one step plus the thing you already computed.

Examples

rewards = [1, 1, 1]
gamma = 0.9
returns [2.71, 1.9, 1.0]
rewards = [0, 0, 10]
gamma = 0.5
returns [2.5, 5.0, 10.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