 nick34992
2/7/2017 - 9:37 PM

## Calculate Mean and Standard Deviation

Calculate Mean and Standard Deviation

``2.1, 3.3, 4.5, 2.6, 3.7, 4.8``
``````#!/usr/bin/env python3.5

from math import sqrt

class Calc_Mean_SD(object):

def parse_comma_file(self, file):
'''Parse comma separated float numbers.'''
float_nums = []
for line in file:
substrs = line.split(',', line.count(','))
for str_var in substrs:
float_nums.append(float(str_var))
return float_nums

def calc_mean(self, numbers):
'''Calculate mean from list of numbers. Iterate through list.
Add each number to sum. Calculate mean. Return mean value.'''
sum = 0.0
for number in numbers:
sum += number
mean = sum / len(numbers)
return mean

def calc_sd(self, numbers, mean):
'''Calculate standard deviation. Iterate through list.
Calculate single deviation, and add to single_dev.'''
deviation = 0.0
single_dev = 0.0
for number in numbers:
single_dev = number - mean
deviation += (single_dev ** 2)
standard_deviation = sqrt(deviation / (len(numbers) -1))
return standard_deviation

def run(self, filename):
in_file = open(filename, 'r')
numbers = self.parse_comma_file(in_file)
mean = self.calc_mean(numbers)
standard_deviation = self.calc_sd(numbers, mean)
print('Mean:', str(mean))
print('Standard Deviation:', str(standard_deviation))
in_file.close()

if __name__ == '__main__':
obj = Calc_Mean_SD()
obj.run('random_floats.txt')

# Mean: 3.5
# Standard Deviation: 1.0526157893552612