Need Help on 7 variance


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


I took a kind of round about way to break down and analyze the problem using this sketch:

grades = [8, 8, 6, 3, 7, 7, 1, 5]
g_sum = sum([x*1.0 for x in grades])
print g_sum
avg = g_sum/len(grades)
print avg
h = [(x - avg)**2 for x in grades]
print h
k = sum(h)/len(h)
print k

The console output looks like this:

[5.640625, 5.640625, 0.140625, 6.890625, 1.890625, 1.890625, 21.390625, 0.390625]

The final value matches what is expected from the SCT when it supplies the above set of grades.

In the sketch I use list comprehensions, but we can reconstruct it with for statements if so desired. From this we can rewrite our grades_sum function,

def grades_sum(scores):
    s = [x*1.0 for x in scores]
    return sum(s)

All the above is doing is making sure that every value in the list is converted to a float before the returned sum. The grades_average function makes a quick call to this one and returns a simple quotient of the return value and the list length.

def grades_average(scores):
    return grades_sum(scores) / len(scores)

Which brings us to our final function in the chain, grades_variance. As constructed from the above sketch we get this...

def grades_variance(scores):
    average = grades_average(scores)
    h = [(x - average)**2 for x in scores]
    variance = sum(h)/len(h)
    return variance

Now it doesn't address any issues that may or may not exist in your code. I chose instead to work on the sketch and let you desconstruct it and adapt to your own code. Hopefully the exercise will enlighten you to any errors or omissions that you can aprise us of, when you get this solved? Please and thanks.