227k views
0 votes
Write the squares function which:

a) to accept an unspecified number of parameters (we assume integer values), and
b) be a generator function
squares should sequentially return (according to a generator function) the square of the difference of each value from the average of all values given to it as input.

In the main program call squares (in any correct way you like) to display the results it returns when given the triplet of values 3,4,5 as input parameters (see examples below). Also use the statistics library to calculate the average.

Execution example: If the triplet of values 3, 4, 5 are given as input parameters then squares will return 1, 0 and 1 consecutively because the average of 3, 4, 5 is 4 and the squares of the difference of each value from the average are 1, 0 and 1 respectively.

Another example: If given as input parameters the square of values 2, 7, 3, 12 then squares will successively return 16, 1, 9, and 36 because the mean is 6 and the squares of the difference of each value from the mean is 16, 1, 9, and 36 respectively.


WHAT TO WATCH OUT FOR
We assume that squares is always given integer values (at least one or more) as input, so you don't need to check for this.
The exercise clearly does not ask that the code be executed multiple times in an iteration loop. Any use of a repeat loop that completely repeats the execution of the program will be considered an error.

1 Answer

4 votes

Here's the code for the squares function as a generator function:

python

import statistics

def squares(*args):

avg = statistics.mean(args)

for arg in args:

yield (arg - avg)**2

In the main program, we can call the squares function with the input parameters and iterate over the results using a for loop:

scss

values = (3, 4, 5)

for square in squares(*values):

print(square)

This will output:

1

0

1

Alternatively, we can call the squares function with a list of values:

scss

values = [2, 7, 3, 12]

for square in squares(*values):

print(square)

This will output:

16

1

9

36

In both cases, the squares function calculates the average of the input values using the statistics library and then yields the square of the difference between each value and the average using a generator function.

User Fede Cugliandolo
by
8.6k points