纯python实现Numpy部分高级运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import time
import random

class PON:
# 求极差
@staticmethod
def range(l):
return max(l) - min(l)
# 求平均数
@staticmethod
def avg(l):
return float(sum(l))/len(l)
# 求中位数
@staticmethod
def median(l):
l = sorted(l)
if len(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
def mode(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
def variance(l): # 平方的期望-期望的平方
s1 = 0
s2 = 0
for i in l:
s1 += i**2
s2 += i
return float(s1)/len(l) - (float(s2)/len(l))**2
# 求方差2
@staticmethod
def variance2(l): # 平方-期望的平方的期望
ex = float(sum(l))/len(l)
s = 0
for i in l:
s += (i-ex)**2
return float(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)))


# 性能测试
arraylist = []
for i in range(1,1000000):
arraylist.append(i)
random.shuffle(arraylist)
time_start = time.time()
print("方差为:{0:.2f}".format(PON.variance(arraylist)))
time_end = time.time()
print("{0}s".format(time_end-time_start))
time_start = time.time()
print("方差为:{0:.2f}".format(PON.variance2(arraylist)))
time_end = time.time()
print("{0}s".format(time_end-time_start))
0%