forked from esitarski/CrossMgr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleCalc.py
224 lines (196 loc) · 5.27 KB
/
SimpleCalc.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import math
import re
tokNum = 'n'
tokError = 'e'
tokEnd = '$'
reTime = re.compile(
'(?:[0-9]+:[0-5][0-9]:[0-5][0-9])|(?:[0-5]?[0-9]:[0-5][0-9])(?:\.[0-9]+)?' )
# ------[HHH]H:MM:SS-------------- ------[M]M:SS--------- ---[.ddddddd]---
reNum = re.compile(
'[0-9]*\.?[0-9]+' )
# [ddd][.]d[ddd]
reWhitespace = re.compile( '[ \r\t]+' )
singleCharTokens = set( c for c in '+-*/()' )
class TimeEvalError( Exception ):
def __init__( self, error, line, col, i ):
self.error = error
self.line = line
self.col = col
self.i = i
def __repr__( self ):
return '%s in %d:%d %d' % self.error, self.line, self.col, self.i
class TimeEvalEmptyExpressionError( TimeEvalError ):
def __init__( self ):
TimeEvalError.__init__( self, 'empty expression', 0, 0, 0 )
class TimeEvalSyntaxError( TimeEvalError ):
def __init__( self, error, line, col, i ):
TimeEvalError.__init__( self, error, line, col, i )
class TimeEvalDivideByZeroError( TimeEvalError ):
def __init__( self, line, col, i ):
TimeEvalError.__init__( self, 'divide by zero error', line, col, i )
class TimeEval( object ):
def __init__( self, str = None ):
self.clear()
def clear( self ):
self.parser = None
self.tok, self.value, self.line, self.col, self.i = None, None, 0, 0, 0
def parse( self, str ):
line, col = 0, 0
i, iMax = 0, len(str)
while i < iMax:
# Skip whitespace.
m = reWhitespace.match( str, i )
if m:
col += len(m.group(0))
i += len(m.group(0))
continue
# Match time format.
m = reTime.match( str, i )
if m:
x = 0.0
for f in m.group(0).split(':'):
x = x * 60.0 + float(f)
yield tokNum, x, line, col, i
col += len(m.group(0))
i += len(m.group(0))
continue
# Match pure numbers.
m = reNum.match( str, i )
if m:
yield tokNum, float(m.group(0)), line, col, i
col += len(m.group(0))
i += len(m.group(0))
continue
c = str[i]
# Process single char tokens.
if c in singleCharTokens:
yield c, None, line, col, i
col += 1
i += 1
continue
# Skip newlines, but adjust the line and col counters.
if c == '\n':
line += 1
col = 1
i += 1
continue
raise TimeEvalSyntaxError( 'invalid char', line, col, i )
yield tokEnd, None, line, col, i
def skip( self ):
self.tok, self.value, self.line, self.col, self.iStr = self.parser.next()
def expr( self ):
x = self.factor()
while self.tok in '+-':
op = self.tok
self.skip()
right = self.factor()
if op == '+':
x += right
else:
x -= right
return x
def factor( self ):
x = self.term()
while self.tok in '*/':
op = self.tok
self.skip()
lineSave, colSave, iStrSave = self.line, self.col, self.iStr
tokSave = self
right = self.factor()
if op == '*':
x *= right
else:
if right == 0.0:
raise TimeEvalDivideByZeroError( lineSave, colSave, iStrSave )
x /= right
return x
def term( self ):
if self.tok == '-':
sgn = -1
self.skip()
else:
sgn = 1
if self.tok == tokNum:
x = self.value
self.skip()
elif self.tok == '(':
self.skip()
x = self.expr()
if self.tok == ')':
self.skip()
else:
raise TimeEvalSyntaxError( 'missing ")"' , self.line, self.col, self.iStr )
else:
if self.tok == tokEnd:
raise TimeEvalSyntaxError( 'incomplete expression', self.line, self.col, self.iStr )
else:
raise TimeEvalSyntaxError( 'invalid token', self.line, self.col, self.iStr )
return sgn * x
def eval( self, str ):
self.clear()
self.parser = self.parse( str )
self.skip()
if self.tok == tokEnd:
raise TimeEvalEmptyExpressionError()
x = self.expr()
if self.tok != tokEnd:
raise TimeEvalSyntaxError( 'unrecognised input', self.line, self.col, self.iStr )
return x
def __call__( self, str ):
return eval( str )
def formatTime( secs, highPrecision = False ):
if secs is None:
secs = 0
if secs < 0:
sign = '-'
secs = -secs
else:
sign = ''
f, ss = math.modf(secs)
secs = int(ss)
hours = int(secs // (60*60))
minutes = int( (secs // 60) % 60 )
secs = (secs % 60) + f
if highPrecision:
secStr = '{:05.2f}'.format( secs )
else:
secStr = '{:02.0f}'.format( secs )
if secStr.startswith('60'):
secStr = '00' + secStr[2:]
minutes += 1
if minutes == 60:
minutes = 0
hours += 1
if hours > 0:
return "{}{}:{:02d}:{}".format(sign, hours, minutes, secStr)
else:
return "{}{:02d}:{}".format(sign, minutes, secStr)
def testEval( str ):
re = TimeEval()
try:
x = formatTime( re.eval(str) )
print str, '=', x
except TimeEvalEmptyExpressionError:
print 'empty expression'
except (TimeEvalSyntaxError, TimeEvalDivideByZeroError) as e:
print str
print ' ' * e.i + '^'
print ' ' * e.i + '|'
print ' ' * e.i + '+---' + e.error
print '--------------------------------------------------------------------'
if __name__ == '__main__':
testEval( '' )
testEval( '3.1415926 * 3.1415926' )
testEval( '-1:00:00' )
testEval( '30:00 - -30:00' )
testEval( '1:00:00 / 12' )
testEval( '1:00:00 * 2.5' )
testEval( '1:75:00 * 2.5' )
testEval( '1:00:00 * (1+3)' )
testEval( '1:00:00 + 10 20' )
testEval( '1:00:00 *' )
testEval( '23542345234523452345.456345634563456' )
testEval( '1:00:00 / (30-20-10)' )
testEval( '1:00:00 / (30-20-10' )
testEval( '1:00:00 + bla / (30-20-10)' )
testEval( '1:0:0 / 2' )