Last active
August 29, 2015 14:08
-
-
Save giwa/7ff7b5fa8597c2fea009 to your computer and use it in GitHub Desktop.
Set of basic statistic operations
This file contains 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
# Set of basic statistics operations | |
# | |
import math | |
def median(items): | |
""" | |
Return median | |
if number of items is odd, return average of 2 middles. | |
>>> items = [10, 2, 5, 7, 4] | |
>>> median(items) | |
4 | |
""" | |
num_items = len(items) | |
if num_items % 2 == 0: | |
return items[num_items - 1] | |
else: | |
m1 = items[int(num_items)] | |
m2 = items[int(num_items) + 1] | |
return (m1 + m2) / 2 | |
def arithmetic_mean(items): | |
""" | |
Return arithmetic mean | |
>>> items = [10, 2, 5, 7, 4] | |
>>> arithmetic_mean(items) | |
5.6 | |
""" | |
return reduce(lambda x, y: x + y, items) / float(len(items)) | |
def sum_of_squares_deviation(items): | |
""" | |
Return sum of squares deviation | |
>>> items = [10, 2, 5, 7, 4] | |
>>> sum_of_squares_deviation(items) | |
37.2 | |
""" | |
ave_items = arithmetic_mean(items) | |
deviation_of_items = map(lambda x: pow(x - ave_items, 2), items) | |
return reduce(lambda x, y: x + y, deviation_of_items) | |
def divergence(items): | |
""" | |
Return divergence | |
>>> items = [10, 2, 5, 7, 4] | |
>>> divergence(items) | |
9.3 | |
""" | |
return sum_of_squares_deviation(items) / (len(items) - 1) | |
def standard_deviation(items): | |
""" | |
Return standard deviation | |
>>> items = [10, 2, 5, 7, 4] | |
>>> round(standard_deviation(items), 2) | |
3.05 | |
""" | |
return math.sqrt(divergence(items)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment