Created
August 26, 2016 15:36
-
-
Save jpotts18/4f99d08133f44b28079e963c837868bc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import division | |
def calculate_mean(numbers): | |
total = sum(numbers) | |
count = len(numbers) | |
return total / count | |
def calculate_median(numbers): | |
sorted_numbers = sorted(numbers) | |
# if our list has a length that is an odd number | |
if len(sorted_numbers) % 2 > 0: | |
# find the center by dividing by 2 and rounding up (e.g. 7 / 2 = 3.5 rounds up to nearest integer 4) | |
middle_number = len(sorted_numbers) / 2 | |
rounded_integer = int(round(middle_number)) | |
return sorted_numbers[rounded_integer] | |
elif len(sorted_numbers) % 2 == 0: # check to see if there are an even number of items in the list | |
# find the center by dividing by 2 to find one of the two middle numbers | |
# (eg. 8 / 2 = 4 then average the 4th and the 5th together) | |
middle_left_number = len(sorted_numbers) / 2 # 4th position | |
middle_right_number = middle_left_number + 1 # 5th position | |
return (middle_left_number + middle_right_number) / 2 | |
else: | |
print('You need to provide a list of numeric types, with a length > 0') | |
def calculate_variance(numbers): | |
# create an empty variance | |
variance = 0 | |
mean = calculate_mean(numbers) | |
# go through each number in the list | |
for number in numbers: | |
# take the difference between the number and the mean | |
# square the difference and add it to variance | |
variance += (number - mean) ** 2 | |
return variance | |
def calculate_standard_deviation(numbers): | |
# a square root is the same as using the 1/2 power | |
return calculate_variance(numbers) ** 0.5 | |
def descriptive_statistics(numbers): | |
# max() and min() are both functions that are implemented in the python language so we don't have to write them. | |
print('Min: {}'.format(min(numbers))) | |
print('Max: {}'.format(max(numbers))) | |
print('Mean: {}'.format(calculate_mean(numbers))) | |
print('Median: {}'.format(calculate_median(numbers))) | |
print('Variance: {}'.format(calculate_variance(numbers))) | |
print('Std Dev: {}'.format(calculate_standard_deviation(numbers))) | |
# a list of numbers | |
numbers = [100, 85, 29, 12, 19.5] | |
print(descriptive_statistics(numbers)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment