classPON: # 求极差 @staticmethod defrange(l): returnmax(l) - min(l) # 求平均数 @staticmethod defavg(l): returnfloat(sum(l))/len(l) # 求中位数 @staticmethod defmedian(l): l = sorted(l) iflen(l)%2 == 1: return l[int(len(l)/2)] else: return (l[int(len(l)/2)-1]+l[int(len(l)/2)]) /2.0 # 求众数 @staticmethod defmode(l): count_dict = {} for i in l: if i in count_dict: count_dict[i] += 1 else: count_dict[i] = 1 max_appear = 0 for v in count_dict.values(): if v > max_appear: max_appear = v if max_appear == 1: return mode_list = [] for k,v in count_dict.items(): if v == max_appear: mode_list.append(k) return mode_list # 求方差 @staticmethod defvariance(l): # 平方的期望-期望的平方 s1 = 0 s2 = 0 for i in l: s1 += i**2 s2 += i returnfloat(s1)/len(l) - (float(s2)/len(l))**2 # 求方差2 @staticmethod defvariance2(l): # 平方-期望的平方的期望 ex = float(sum(l))/len(l) s = 0 for i in l: s += (i-ex)**2 returnfloat(s)/len(l) # 主函数,测试 arr = [1,2,3,2,3,1,4] print("极差为:{0}".format(PON.range(arr))) print("平均数为:{0:.2f}".format(PON.avg(arr))) print("中位数为:{0}".format(PON.median(arr))) print("众数为:{0}".format(PON.mode(arr))) print("方差为:{0:.2f}".format(PON.variance(arr))) print("方差为:{0:.2f}".format(PON.variance2(arr)))