Home > Net >  Problem with for loops and float' object is not a iterable
Problem with for loops and float' object is not a iterable

Time:03-30

I was trying to solve a variance problem, but after the for loop I can't the sum values to finally dived by the numbers of items in the list.

lista = [1.86, 1.97, 2.05, 1.91, 1.80, 1.78]

n = len(lista)         #NUMBERS OF DATA IN THE LIST
MA = sum(lista)/n      #ARITHMETIC MEAN

for x in lista:
     y = pow(x - MA, 2)    #SUBTRACTION OF ALL DATA BY THE MA, RAISED TO THE POWER OF 2
     print(y)
print(sum(y)/n)       # AND THAT IS IT, I CAN'T FINISH

I‘m trying to do this work for days and I didn't discovery yet. Is it possible to finish or should I just quit it because there are better ways to solve it?

The result of the variance must be: 0.008891666666666652

PS: I don't want to have to install other programs or libs like pandas or numpy

CodePudding user response:

You are just updating the value of y each time you run the loop so y will be a single element after it reached end of loop.

What you are printing is :

sum(pow(1.78 - MA, 2)/2) 

So either you store each value of y inside function in a array of simply do a thing

y=0
y = pow(x-ma, 2) 
y  = y

CodePudding user response:

I did it again and found the result, thanks Deepak Singh for your help, the asnwer is:

lista = [1.86, 1.97, 2.05, 1.91, 1.80, 1.78]

n = len(lista)
MA = sum(lista)/n
y = 0

for x in lista:
     subts = pow(x - MA, 2)
     y = (y   subts)

print("Varience:", y/n)
  • Related