Issue
Can we shorter this code without using :=
because my python version is lower than 3.8
?
arr = [3,2,1,0]
ml = .7
arrSum = 0
res = []
for a in reversed(arr):
arrSum = a + ml*arrSum
res.append(arrSum)
res[::-1]
# [4.89, 2.7, 1.0, 0.0]
with :=
:
>>> arrSum = 0
>>> [arrSum := a + ml*arrSum for a in reversed(arr)][::-1]
[4.89, 2.7, 1.0, 0.0]
It's Okay If solution be with numpy
or ... .
Solution
You can use e.g. itertools
:
from itertools import accumulate
ml = 0.7
arr = [3, 2, 1, 0]
list(accumulate(arr[::-1], lambda x,y: ml * x + y))[::-1]
It gives:
[4.89, 2.7, 1.0, 0]
numpy
is another option:
import numpy as np
np.convolve(ml**np.arange(len(arr)), arr[::-1])[len(arr)-1::-1]
Answered By - bb1
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.