I need to make a function which will return successively as a generator, the square of the difference of each value from the average of all the values given as input.
The function must
A) accept an undefined number of parameters
B) be a generator function
The values will be integers.
To calculate the average of all values I can import statistics.
Have you got any idea?
The code I tried to write:
import statistics
def squares(*args):
for i in args:
a=(args-av)**2
yield a
lst=[]
count = int(input("Give the amount of numbers: "))
for i in range (0,count):
ele=int(input())
lst.append(ele)
av=statistics.mean(lst)
for i in squares(*lst):
print(i)
CodePudding user response:
The only error in your script comes from using args
instead of i
in your calculations:
import statistics
def squares(*args):
for i in args:
a=(i-av)**2 # <-- There.
yield a
lst=[]
count = int(input("Give the amount of numbers: "))
for i in range (0,count):
ele=int(input())
lst.append(ele)
av=statistics.mean(lst)
for i in squares(*lst):
print(i)
I would also advise using def squares(av, *args)
just so that your av
does not come out of somewhere. You then have to modify your last but one line to for i in squares(av, *lst)
. Otherwise everything looks ok!
My suggestion:
import statistics
def squares(average, *items):
for item in items:
yield (item - average)**2
lst = []
count = int(input("Give the amount of numbers: "))
for _ in range(count):
item = int(input())
lst.append(item)
average = statistics.mean(lst)
for square in squares(average, *lst):
print(square)
CodePudding user response:
Your av
variable should be computed inside the generator function:
def squares(*args):
av = sum(args)/len(args)
for a in args:
yield (a-av)**2