Compute discounted returns for an episode
In RL a reward now is worth more than the same reward later. The return from step t is G_t = r_t + gamma r_{t+1} + gamma^2 r_{t+2} + ...
Write discounted_returns(rewards, gamma, dones=None). Return a list of G_t for every step. If dones is given, dones[t] = True means the episode ended after step t, so the sum must not continue past it (a new episode starts at t + 1).
def discounted_returns(rewards, gamma, dones=None)Understand the idea
In reinforcement learning, a reward received later is worth a bit less than one received now, like money today versus next year. The return G_t adds the reward at step t plus gamma times the next reward, plus gamma squared times the one after, and so on. Going backwards makes it one pass: G_t = r_t + gamma x G_{t+1}. When an episode ends after step t, the sum must not continue into the next episode. Worked example: rewards [1, 1, 1], gamma 0.9. G_2 = 1. G_1 = 1 + 0.9 x 1 = 1.9. G_0 = 1 + 0.9 x 1.9 = 2.71. With dones [False, True, False], the episode ends after step 1: G_2 = 1, G_1 = 1 (no future), G_0 = 1 + 0.9 x 1 = 1.9. Rule: walk from the end with running = 0; if dones[t], reset running before adding; running = r_t + gamma x running; G_t = running. Policy gradient methods like REINFORCE use these returns.