码迷,mamicode.com
首页 > 编程语言 > 详细

python 实现求和、计数、最大最小值、平均值、中位数、标准偏差、百分比。

时间:2014-07-16 18:06:48      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:blog   for   div   re   c   python   

import sys
 
class Stats:
 
    def __init__(self, sequence):
        # sequence of numbers we will process
        # convert all items to floats for numerical processing
        self.sequence = [float(item) for item in sequence]
 
    def sum(self):
        if len(self.sequence) < 1:
            return None
        else:
            return sum(self.sequence)
 
    def count(self):
        return len(self.sequence)
 
    def min(self):
        if len(self.sequence) < 1:
            return None
        else:
            return min(self.sequence)
 
    def max(self):
        if len(self.sequence) < 1:
            return None
        else:
            return max(self.sequence)
 
    def avg(self):
        if len(self.sequence) < 1:
            return None
        else:
            return sum(self.sequence) / len(self.sequence)    
 
    def median(self):
        if len(self.sequence) < 1:
            return None
        else:
            self.sequence.sort()
            return self.sequence[len(self.sequence) // 2]
 
    def stdev(self):
        if len(self.sequence) < 1:
            return None
        else:
            avg = self.avg()
            sdsq = sum([(i - avg) ** 2 for i in self.sequence])
            stdev = (sdsq / (len(self.sequence) - 1)) ** .5
            return stdev
 
    def percentile(self, percentile):
        if len(self.sequence) < 1:
            value = None
        elif (percentile >= 100):
            sys.stderr.write(‘ERROR: percentile must be < 100.  you supplied: %s\n‘% percentile)
            value = None
        else:
            element_idx = int(len(self.sequence) * (percentile / 100.0))
            self.sequence.sort()
            value = self.sequence[element_idx]
        return value

  

python 实现求和、计数、最大最小值、平均值、中位数、标准偏差、百分比。,布布扣,bubuko.com

python 实现求和、计数、最大最小值、平均值、中位数、标准偏差、百分比。

标签:blog   for   div   re   c   python   

原文地址:http://www.cnblogs.com/huangxiaohen/p/3847348.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!