The Variance


Oops, try again. grades_variance([9, 9, 5, 9, 0, 5, 4]) returned 0.61197657 instead of the expected: 9.8367346939

I followed all the instructions! What's wrong?

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


That line should be part of the return, not inside the loop.

That line is unreachable (since it follows return and should not be indented.


Why does the division part work when placed with the return?


We need to have the full summation before we divide by the number of terms. The quotient should be a fairly large number since it is still the square of sigma (standard deviation).


Could you describe it in a simpler way. Why does the division part not work whilst in the loop??


We need to have added n items before dividing by n. Think of taking an average of a list of values. Do we divide by n each time we add another value? No. We wait until we have a total, then divide by the number of terms.

Variance is a type of average, only it is the average of the squares of the differences around the mean. We square it so the sign has no bearing. Both negative and positive numbers are positive when they are squared.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.