LearnFrenzy
Sign in Take a free test

Iterators and Generators · Iterators and Generators Coding Problems · Question 8

A running average coroutine with send() in Python Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Write a generator that receives readings with send() and yields the running average and the maximum so far; feed it a list of temperatures.

Solution
main.py Run
def tracker():
    total = count = 0
    highest = None
    result = None
    while True:
        value = yield result
        total += value
        count += 1
        highest = value if highest is None else max(highest, value)
        result = (round(total / count, 2), highest)

t = tracker()
next(t)                                   # prime the generator
for temp in [31.5, 33.0, 29.5, 35.0]:
    avg, high = t.send(temp)
    print(f"{temp}: average {avg}, highest {high}")

Output Verified by running it on Python 3

31.5: average 31.5, highest 31.5
33.0: average 32.25, highest 33.0
29.5: average 31.33, highest 33.0
35.0: average 32.25, highest 35.0

The generator keeps its state between sends. next() runs it to the first yield so that each send() has a paused yield to resume.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links