0

I'm having problem finding function similar to cumulative sum only I want it weighted. So with an external for loop would look something like this:

discount_rate = 0.95 
rewards = [0, 0, 10] # want to translate to: [9, 9.5, 10] (approximation)

reversed_rewards = [10, 0, 0]
new_rewards = [0] * len( rewards)

previus = 0
for index in range( len( rewards)):
     new_rewards[ index] = reversed_rewards[ index] + previus * discount_rate
     previus = new_rewards[ index]

print( list( reversed( new_rewards)))

But this is kind of slow version if you have large reward array. Is there any existing function that would do this faster?

poppytop
  • 341
  • 1
  • 12
  • 4
    Duplicate - https://stackoverflow.com/questions/47970683/vectorize-a-numpy-discount-calculation? – Divakar Jan 04 '18 at 13:39
  • It does kinda look like a dupe, but despite having the `numpy` tag this question doesn't actually use numpy as currently written. – kojiro Jan 04 '18 at 13:41

1 Answers1

1

NOTE: I'm using Python 3.6.0

You can try using itertools: https://docs.python.org/3/library/itertools.html

The itertools.accumulate function was shown to possibly be faster than np.cumsum: https://stackoverflow.com/a/39534850/7175945

from itertools import accumulate

def weighted():
    discount_rate = 0.95 #your discount rate
    rewards = [0, 0, 10] # want to translate to: [9, 9.5, 10](approximation)
    reversed_rewards = rewards[::-1] #list reversal
    acc = list(accumulate(reversed_rewards, lambda x,y: x*discount_rate + y))
    return acc[::-1] 

print(weighted())

I think this should be what you're looking for if you truly don't want to use numpy, otherwise what you already have written is also a viable option.

Dascienz
  • 1,071
  • 9
  • 14