[英]Weighted cumulative sum python
我在查找類似於累積總和的函數時遇到問題,只是我希望對它加權。 因此,使用外部for循環看起來像這樣:
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)))
但是,如果您有較大的獎勵陣列,則這是一種慢速版本。 是否有任何現有功能可以更快地做到這一點?
注意:我正在使用Python 3.6.0
您可以嘗試使用itertools
: https : itertools
結果表明itertools.accumulate
函數可能比np.cumsum
更快: https : np.cumsum
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())
我認為如果您真的不想使用numpy
,那么這應該是您正在尋找的東西,否則您已經編寫的內容也是可行的選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.