finding the variance and standard deviation of a list of numbers in python

Solutions on MaxInterview for finding the variance and standard deviation of a list of numbers in python by the best coders in the world

showing results for - "finding the variance and standard deviation of a list of numbers in python"
Luka
14 Sep 2019
1# Finding the Variance and Standard Deviation of a list of numbers
2
3def calculate_mean(n):
4    s = sum(n)
5    N = len(n)
6    # Calculate the mean
7    mean = s / N 
8    return mean 
9
10def find_differences(n):
11    #Find the mean
12    mean = calculate_mean(n)
13    # Find the differences from the mean
14    diff = []
15    for num in n:
16        diff.append(num-mean)
17    return diff
18
19def calculate_variance(n):
20    diff = find_differences(n)
21    squared_diff = []
22    # Find the squared differences
23    for d in diff:
24        squared_diff.append(d**2)
25    # Find the variance
26    sum_squared_diff = sum(squared_diff)
27    variance = sum_squared_diff / len(n)
28    return variance
29
30if __name__ == '__main__':
31    donations = [100, 60, 70, 900, 100, 200, 500, 500, 503, 600, 1000, 1200]
32    variance = calculate_variance(donations)
33    print('The variance of the list of numbers is {0}'.format(variance))
34    
35    std = variance ** 0.5
36    print('The standard deviation of the list of numbers is {0}'.format(std))
37#src : Doing Math With Python