-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
safe.py
129 lines (94 loc) · 2.76 KB
/
safe.py
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# make / work consistently between python 2.x and 3.x
# https://www.python.org/dev/peps/pep-0238/
from __future__ import division
from functools import reduce
import math
def safeSum(values):
safeValues = [v for v in values if v is not None]
if safeValues:
return sum(safeValues)
def safeDiff(values):
safeValues = [v for v in values if v is not None]
if safeValues:
values = list(map(lambda x: x*-1, safeValues[1:]))
values.insert(0, safeValues[0])
return sum(values)
def safeLen(values):
return len([v for v in values if v is not None])
def safeDiv(a, b):
if a is None: return None
if b in (0,None): return None
return a / b
def safeExp(a):
try:
return math.exp(a)
except TypeError:
return None
def safePow(a, b):
if a is None or b is None:
return None
try:
result = math.pow(a, b)
except (ValueError, OverflowError):
return None
return result
def safeMul(*factors):
if None in factors:
return None
factors = [float(x) for x in factors]
product = reduce(lambda x,y: x*y, factors)
return product
def safeSubtract(a,b):
if a is None or b is None:
return None
return float(a) - float(b)
def safeAvg(values):
safeValues = [v for v in values if v is not None]
if safeValues:
return sum(safeValues) / len(safeValues)
def safeAvgZero(values):
if values:
return sum([0 if v is None else v for v in values]) / len(values)
def safeMedian(values):
safeValues = [v for v in values if v is not None]
if safeValues:
sortedVals = sorted(safeValues)
mid = len(sortedVals) // 2
if len(sortedVals) % 2 == 0:
return float(sortedVals[mid-1] + sortedVals[mid]) / 2
else:
return sortedVals[mid]
def safeStdDev(a):
sm = safeSum(a)
ln = safeLen(a)
avg = safeDiv(sm,ln)
if avg is None:
return None
sum = 0
safeValues = [v for v in a if v is not None]
for val in safeValues:
sum = sum + (val - avg) * (val - avg)
return math.sqrt(sum/ln)
def safeLast(values):
for v in reversed(values):
if v is not None: return v
def safeMin(values, default=None):
safeValues = [v for v in values if v is not None]
if safeValues:
return min(safeValues)
else:
return default
def safeMax(values, default=None):
safeValues = [v for v in values if v is not None]
if safeValues:
return max(safeValues)
else:
return default
def safeMap(function, values):
safeValues = [v for v in values if v is not None]
if safeValues:
return [function(x) for x in safeValues]
def safeAbs(value):
if value is None:
return None
return abs(value)