-2

I want to calculate the variance of values in list x1. Could anyone fix the error in this code?!

def my_mean(L):
    s = 0
    for i in range(0, len(L)):
        s = s + L[i]
    return s / len(L)
def my_var(L):
    t = 0
    for i in range(0, len(L)):
        t = t + L[i] - def my_mean(L) 
    return t*t / len (L)

x1 = [1, 3, 4, -3, 8]
v1 = my_var(x1)
print(v1)
JJJ
  • 32,902
  • 20
  • 89
  • 102
  • 4
    What error? Do you get error messages? Does it give wrong results? If so, what's the input, expected output and the actual output? – JJJ Jun 20 '17 at 09:17
  • You should read [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Rory Daulton Jun 20 '17 at 09:40
  • I need to use variance equation to solve value in x1 list. could you recommend any modification of the code?! – Hero Hamada Jun 20 '17 at 11:10

1 Answers1

1

You need to use the def keyword only when you define the function.

When you call to the function you don't need to use def again.

Fix this row:

t = t + L[i] - def my_mean(L) 

To:

t = t + L[i] - my_mean(L) 
omri_saadon
  • 10,193
  • 7
  • 33
  • 58
  • it still has a problem but now it gives a result as below but I need to establish variance equation in my code. can you recommend any modification?! 3.944304526105059e-32 0.0 – Hero Hamada Jun 20 '17 at 11:09
  • 1
    @HeroHamada, try read this [question](https://stackoverflow.com/questions/35583302/how-can-i-calculate-the-variance-of-a-list-in-python).. you can assist the numpy lib. – omri_saadon Jun 20 '17 at 11:22
  • I think I am getting closer but still not work def my_var(L): s = 0 t = 0 u = 0 for i in range(0, len(L)): s += L[i] t = s/len(L) u = (L[i]-t)*(L[i]-t) return u / len(L) x1 = [1, 3, 4, -3, 8] x2 = [1, -4, 7, 2] v1 = my_var(x1) v2 = my_var(x2) print(v1) print(v2) – Hero Hamada Jun 20 '17 at 13:40