Write a generator that keeps a running average of values sent to it.
Output
10.0 15.0 30.0
Approach
value = yield result receives what send() passes.
Solution
Python
defaverager():total,count,average=0,0,NonewhileTrue:value=yieldaveragetotal+=valuecount+=1average=total/countavg=averager()next(avg)# start the generatorprint(avg.send(10),avg.send(20),avg.send(60))
Output
10.0 15.0 30.0
Line by line
Line 4
The generator pauses here, hands out the current average and waits for the next value.
Line 10
The first next() runs the code up to the first yield.
Learn the concept
New to this topic? Read the lesson, then come back.