Question

I've written a function to find the standard deviation of a list:

def avg(L):
    return sum(L)/len(L)

def stdDev(L):
    for i in range(len(L)-1):
        return sqrt((sum(L[i]-avg(L)))**2)/len(L))

If I run this and give the Shell the input [20,10,30] it says "float object is not iterable". Where is the issue, and can I solve it without settling for integer results of either of these functions?

Was it helpful?

Solution

sum(L[i]-avg(L)) - here you have a sum of float.

You also have return statement every pass of the loop, that's clearly wrong.

Formula for standard deviation also is not right, as you misplaced the braces.

What I believe you wanted:

def stdDev(L):
    s = 0
    for i in range(len(L)):
        s += (L[i] - avg(L))**2
    return sqrt(s/len(L))

Better to iterate through elements than their indices:

    for x in L:
        s += (x - avg(L))**2

or

def stdDev(L):
    ave = avg(L)
    s = sum((x - ave)**2 for x in L)
    return sqrt(s/len(L))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top