EvilTwin
EvilTwin

Reputation: 31

how to print args from a Generator in Python?

i wanna solve a subject in my University so, i have to create a function with parametres(*args). After that i have to find the average of all of them. Continues with a math type.. we have to print out the square of abstraction per-element - average and i have to use a Generator. For e.g: i have the function "squares(*args). when i call it like "squares(3,4,5) we find the average, 4 for this e.g and we start the abstraction. 3-4 , 4,4, 5,-4 but also we need the square of it. So (3-4)**2 and etc. I have this code but.. doesn't work, any idea?

from statistics import mean
def squares(*args):
  avg=mean(args)
  i = 0
  while (i <= len(args)):
    yield (args[i]-avg)**2
    i=i+1
squares(2, 7, 3, 12)
for k in squares():
  print(k)

Upvotes: 0

Views: 217

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Issue here:

squares(2, 7, 3, 12)
for k in squares():
  print(k)

you're calling squares() a first time - which returns a generator object that you discard (you don't assign it to a variable). Then you call it a second time and iterate over the returned generator, but since you didn't pass any argument the genrator is "empty" (it has nothing to yield) and the for loop's body doesn't execute.

IOW, replace this with:

squared = squares(2, 7, 3, 12)
for k in squared:
  print(k)

Or just simply:

for k in squares(2, 7, 3, 12):
  print(k)

NB: I didn't test you code, it might have other issues...

Upvotes: 2

Related Questions