7. The Variance


#1
`grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def print_grades(grades):
    for grade in grades:
        print grade

def grades_sum(grades):
    total = 0
    for grade in grades: 
        total += grade
    return total
    
def grades_average(grades):
    sum_of_grades = grades_sum(grades)
    average = sum_of_grades / float(len(grades))
    return average

def grades_variance(scores):
    average = grades_average(scores)
    variance = 0
    for i in scores:
        variance = ((average - i) ** 2.0)
        variance = variance / len(scores)
    return variance
    
print grades_variance(grades)`

error: Oops, try again. grades_variance([9, 5, 0]) returned 7.2592592593 instead of the expected: 13.5555555556

Help :<


The Variance
#2

Indent problem on the divison of variance.


#3

one more problem one 4th last line
variance = ((average - i) ** 2.0) should be variance += ((average - i) ** 2.0)


#4

One more problem if you look at line 3rd last line variance = variance / len(scores) you probably should change the variable name because it gonna change the variance. just name it something different like new_var = variance / len(scores)
return new_var
or change the indentation of the variance


#5
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def print_grades(grades):
    for grade in grades:
        print grade

def grades_sum(grades):
    total = 0
    for grade in grades: 
        total += grade
    return total
    
def grades_average(grades):
    sum_of_grades = grades_sum(grades)
    average = sum_of_grades / float(len(grades))
    return average

def grades_variance(scores):
    average = grades_average(scores)
    variance = 0
    for score in scores:
        square_diff = (average - score) ** 2
        variance += square_diff
    total_variance = variance / len(scores)
    return total_variance
    
print grades_variance(grades)

#6

You are correct, but you can be slightly more succinct, this version also works and it's a bit shorter:

def grades_variance(scores):
    average = grades_average(scores)
    variance = 0
    for score in scores:
        variance += ((average - score) ** 2)
    return variance / len(scores)

#7

Thank you!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


#8

It should be out of the for loop


#9

Can anyone tell me how I should indent?

variance = variance / len(scores)

I don't understand because it gives me an unexpected indent error if I increase it or decrease it. Also, why does that error change the variance every time you run the code?


#10

hello kindly check the formula for variance

you may just get the answer.!
take care