PIXELBANKv9.1.0
Menu

Reward-to-Go for Every Timestep

Problem Statement

Return the discounted reward-to-go G_t for every timestep of an episode, not just the first:

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

Implement rewards_to_go(rewards, gamma) returning a list the same length as rewards, where element t is G_t.

Example:

Input:
rewards_to_go([1.0, 2.0, 3.0], 1.0)
Output:
[6.0, 5.0, 3.0]
Reasoning:
  • We compute the reward-to-go GtG_t in reverse order (from the last timestep to the first) because each GtG_t depends on the subsequent Gt+1G_{t+1} via the recurrence Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}.
  • Starting at the final timestep t=2t=2 with reward R3=3.0R_3 = 3.0 and no future rewards, the accumulated value is simply G2=3.0+1.0â‹…0=3.0G_2 = 3.0 + 1.0 \cdot 0 = 3.0.
  • Moving to t=1t=1 with reward R2=2.0R_2 = 2.0, we add the current reward to the discounted future value: G1=2.0+1.0â‹…3.0=5.0G_1 = 2.0 + 1.0 \cdot 3.0 = 5.0.
  • At the initial timestep t=0t=0 with reward R1=1.0R_1 = 1.0, we again combine the current reward with the discounted next value: G0=1.0+1.0â‹…5.0=6.0G_0 = 1.0 + 1.0 \cdot 5.0 = 6.0.
  • The final output is [6.0, 5.0, 3.0]

Constraints:

  • 0 <= len(rewards) <= 10000, 0.0 <= gamma <= 1.0
  • Compute in a single backward pass (O(n)).
  • Empty input returns an empty list.
🔒

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.
Reward-to-Go for Every Timestep - Medium | PixelBank