Send values into a generator

MediumIterator & Generator Programs · 18 of 20

Write a generator that keeps a running average of values sent to it.

Advertisement
Output
10.0 15.0 30.0

Approach

  1. value = yield result receives what send() passes.

Solution

Python
def averager():    total, count, average = 0, 0, None    while True:        value = yield average        total += value        count += 1        average = total / count avg = 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.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment