Variance


#1



Hi. I'm totally stuck and had no idea what to do next. Can anyone please help me? My code 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(grades)
    variance = 0
    for score in scores:
        n = (average - score) ** 2.0
        total = variance + n
    result = total / len(scores)
    return result


print (grades_variance(grades))


#2

here:

average = grades_average(grades)

because you use grades your function only works for a single list and not for any list supplied as argument on function call.


#3

Okay, I've changed it from grades to scores and I still get the same error:

"Oops, try again. grades_variance([5, 2, 6, 1, 5, 1, 0, 7]) returned 1.642578125 instead of the expected: 6.234375"


#4

here:

total = variance + n

please explain. total isn't defined before, so this will simply contain the last value of n, not the total variance


#5

Omg, you're right. Thank you so much!

My code looks like this right now and everything is working:

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:
        n = (average - score) ** 2.0
        variance += n
    result = variance / len(scores)
    return result


print (grades_variance(grades))

#6

and you realized you needed to change result = total / len(scores) as well, well done

At least you are understanding what you are doing :slight_smile: With just a little nudge from me, you solved your problem, well done :slight_smile:


#7

Thank you one more time for very quick response :slight_smile: Have a great weekend!


#8

you're welcome :slight_smile: You too!


#9

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