Home > database >  What is alternative for `:=` in lower python version for this for-loop?
What is alternative for `:=` in lower python version for this for-loop?

Time:12-12

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 ... .

CodePudding user response:

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]

CodePudding user response:

arrSum = 0
[arrSum := a   ml*arrSum for a in reversed(arr)][::-1]

could be rewritten as

arrsum = 0

def fn(x):
   nonlocal arrsum   # or 'global arrsum' depending on the context
   arrsum = x
   return x

[fn(a   ml*arrSum) for a in reversed(arr)][::-1]

Not saying that it is a good idea to do this ... but this is a direct way to simulate := in an earlier Python version.

  • Related