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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!