Find the cumulative average of the list [8,1,4,2,1] using accumulate() and lambda function in python

Viewed 1715

Hi I am new to python I want to find the cummulative average of the given list using accumulate() and lambda function i have written code till accumulate() but I can't find the cummulative average using lambda function. Can anyone help me with it ?

enter code here
a= [8,1,4,2,6]
import itertools as it
l=[]
l = it.accumulate(a)
print(list(l))


My output should be like this [4.5,4.33,3.75,4.2]
2 Answers

Using accumulate is surely not the easiest/cleanest way to calculate a cumulative average. But you can do it for the fun. You'd have to apply it on enumerate(a) though since the lambda function has no idea of the position of its arguments in the list:

a= [8,1,4,2,6]
import itertools as it
l=[]
l = it.accumulate(list(enumerate(a)), lambda x,y: (y[0], (x[1]*(x[0]+1) + y[1])/(y[0]+1)))
print(list(map(lambda x: x[1], l)))
from  itertools import accumulate
result=accumulate([8,1,4,2,6],lambda x,y:(x+y)/2)
for res in result :
    print(res)
Related