7. The Variance


#1

I finished this course a while back but I wanted to look into what this line really does in retro spect to the whole piece of code.

variance += (average - score) ** 2

"""The whole piece of code is below"""

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:
        variance += (average - sore) ** 2

#2
for score in scores:
       variance += (average - score) ** 2

is simply how you calculate the variance (without taking the average for some reason).
https://en.wikipedia.org/wiki/Variance

Writing this as something like

 variance = sum(( (average - score) ** 2 for score in scores ))

Would probably be a more "pythonic" way of doing it.


#3

The mentioned line is to calculate the square of differences for each value from the mean.


#4

:grinning: Thank you so much!! @codeninja84962


#6

Is their a problem with your code? Or you're just posting for it to be viewed?


#7

No thank you all excellent