w3resource

Python Running Average Generator: Calculate the average of a sequence


16. Running Average Generator

Write a Python program to implement a generator function that generates the running average of a sequence of numbers.

Sample Solution:

Python Code:

def running_average_generator():
    total = 0
    count = 0
    while True:
        value = yield total / count if count > 0 else 0
        total += value
        count += 1

# Create the generator object
running_avg_gen = running_average_generator()

# Prime the generator
next(running_avg_gen)

# Accept input from the user
print("Input a sequence of numbers (Press Enter & 'e' to quit):")
while True:
    num = input("> ")
    if num.lower() == 'e':
        break
    value = float(num)
    average = running_avg_gen.send(value)
    print("Running Average:", average)

Sample Output:

Input a sequence of numbers (Press Enter & 'e' to quit):
> 5
Running Average: 5.0
> 6
Running Average: 5.5
> 7
Running Average: 6.0
> e
Input a sequence of numbers (Press Enter & 'e' to quit):
> -1
Running Average: -1.0
> -2
Running Average: -1.5
> -3
Running Average: -2.0
> -4
Running Average: -2.5
> e

Explanation:

In the above exercise,

The generator function running_average_generator() maintains a running total (total) and count (count) of the numbers received. It continuously yields the running average by dividing the total by the count (if count > 0) or 0 if count is 0.

We create the generator object running_avg_gen and prime it by calling next(running_avg_gen) before entering the input loop. We accept a sequence of numbers from the user until they enter 'e' to quit. Each number is sent to the generator using the send() method, and the running average is printed.

Flowchart:

Flowchart: Calculate the average of a sequence.

For more Practice: Solve these Related Problems:

  • Write a Python program to create a generator that yields the running average of numbers from a given list, printing each intermediate average.
  • Write a Python function that computes the cumulative average of an iterable using a generator and then returns the final average.
  • Write a Python script to generate the running average of user-provided numbers and then print all intermediate averages.
  • Write a Python program to calculate the running average for a stream of data and verify the result by comparing it with the final average computed traditionally.

Go to:


Previous: Generate factors for a number.
Next: Generate the powers of a number.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.