-
Notifications
You must be signed in to change notification settings - Fork 1
/
calc.py
1891 lines (1556 loc) · 69.6 KB
/
calc.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
calc: A general-purpose, feature-rich calculator module
Compatible with Python 2.6+ and Python 3.
Legal
=====
All code, unless otherwise indicated, is original, and subject to the terms of
the attached licensing agreement.
Copyright (c) Neil Tallim, 2002-2019
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import collections
import functools
import math
import numbers
import re
import random
#Python3 compatibility
try:
basestring
except NameError:
basestring = str
#Constants
########################################
_IDENTITIFER_PATTERN = r"(?:[A-Za-z_]+|`.+?`)" #: Patterns that can be used for a variable/function name.
_NUMERIC_REGEXP = re.compile(r"^(\d+(?:\.\d+)?|\.\d+)") #: Matches numeric entities.
_FUNCTION_REGEXP = re.compile(r"^(%s)\(" % (_IDENTITIFER_PATTERN)) #: Matches function entities.
_VARIABLE_REGEXP = re.compile(r"^(%s)" % (_IDENTITIFER_PATTERN)) #: Matches variable entities.
_LINE_FUNCTION_REGEXP = re.compile(r"^(%s)\(\s*(?:((?:%s,\s*)*%s)\s*)?\)\s*=\s*(.+)$" % (_IDENTITIFER_PATTERN, _IDENTITIFER_PATTERN, _IDENTITIFER_PATTERN)) #: Determines whether a line is a function.
_LINE_VARIABLE_REGEXP = re.compile(r"^(%s)\s*=\s*(.+)$" % (_IDENTITIFER_PATTERN)) #: Determines whether a line is a variable.
_LINE_EQUATION = 0 #: Indicates that a line seems to be an equation.
_LINE_FUNCTION = 1 #: Indicates that a line seems to be a function.
_LINE_VARIABLE = 2 #: Indicates that a line seems to be a variable.
_FUNCTION_CUSTOM = 0 #: Indicates that a token is a custom function.
_FUNCTION_BUILTIN = 1 #: Indicates that a token is a built-in function.
_FUNCTION_EXTERNAL = 2 #: Indicates that the token is an external function.
_VARIABLE_CUSTOM = 10 #: Indicates that a token is a custom variable.
_VARIABLE_BUILTIN = 11 #: Indicates that a token is a built-in variable.
_VARIABLE_EXTERNAL = 12 #: Indicates that a token is an external variable.
_FUNCTION_PREFIX = 'f' #: Indicates that a token starts a function block.
_PARAMETER_PREFIX = 'p' #: Indicates that a token is a function parameter.
_VARIABLE_PREFIX = 'v' #: Indicates that a token is a variable.
_NEGATION_DISABLER = (')', _FUNCTION_PREFIX, _PARAMETER_PREFIX, _VARIABLE_PREFIX) #: Upon reaching these, reset the negation evaluator.
_FUNCTION_DELIMITER = ',' #: Separates function parameters.
_NEGATION_MULTIPLIER = '*' #: Used to ensure negation gets applied first.
_PURE_OPERATORS = ('^', '*', '/', '\\', '%', '+', '-', '<', '>', _NEGATION_MULTIPLIER) #: Perform basic mathematical functions.
_OPERATORS = tuple(list(_PURE_OPERATORS) + ['(', ')']) #: Have significance to the structure of mathematical formulas.
_ALLOWED_TOKENS = tuple(list(_OPERATORS) + [_FUNCTION_DELIMITER]) #: All permitted standalone tokens.
_OPERATOR_PRECEDENCE = {
_NEGATION_MULTIPLIER: 100,
'^': 9,
'*': 8,
'/': 8,
'\\': 8,
'%': 8,
'+': 6,
'-': 6,
'<': 1,
'>': 1,
'(': -1,
')': 0
} #: The order in which operators should resolve.
#Built-in properties
########################################
_VARIABLES = {
'e': (_VARIABLE_BUILTIN, math.e),
'pi': (_VARIABLE_BUILTIN, math.pi),
} #: Pre-defined variables.
def _generateBuiltinFunctions():
"""
This function populates the catalogue of built-in calculation functions.
It is deleted immediately after execution is complete.
All functions it defines take a sequence of numbers on which they will
operate, returning a computed value when done.
@return: A dictionary keyed by arity of dictionaries that contain
built-in calculation functions.
"""
functions = {
}
def _abs(args):
return abs(args[0])
functions[(1, 'abs')] = _abs
def _acos(args):
return math.acos(args[0])
functions[(1, 'acos')] = _acos
def _asin(args):
return math.asin(args[0])
functions[(1, 'asin')] = _asin
def _atan(args):
return math.atan(args[0])
functions[(1, 'atan')] = _atan
def _atan2(args):
return math.atan2(args[0], args[1])
functions[(2, 'atan')] = _atan2
def _ceil(args):
return int(math.ceil(args[0]))
functions[(1, 'ceil')] = _ceil
def _cos(args):
return math.cos(args[0])
functions[(1, 'cos')] = _cos
def _degrees(args):
return math.degrees(args[0])
functions[(1, 'degrees')] = _degrees
def _e(args):
if args[1] > 9999:
raise ThresholdError("Exponents have been limited to prevent abuse. e() caps at 9999.")
return args[0] * (10 ** args[1])
functions[(2, 'e')] = _e
def _fact(args):
if args[0] <= 1:
return 1
elif args[0] > 100:
raise ThresholdError("Value passed to fact() (%i) is too large. Use 100 or less." % args[0])
return functools.reduce(lambda x, y:x*y, range(1, args[0] + 1))
functions[(1, 'fact')] = _fact
def _floor(args):
return int(math.floor(args[0]))
functions[(1, 'floor')] = _floor
def _ln(args):
return math.log(args[0], math.e)
functions[(1, 'ln')] = _ln
def _log(args):
return math.log(args[0])
functions[(1, 'log')] = _log
def _log2(args):
return math.log(args[0], args[1])
functions[(2, 'log')] = _log2
def _ncr(args):
return (_fact((args[0],)) / (_fact((args[1],)) * _fact((args[0] - args[1],))))
functions[(2, 'ncr')] = _ncr
def _npr(args):
return (_fact((args[0],)) / _fact((args[0] - args[1],)))
functions[(2, 'npr')] = _npr
def _radians(args):
return math.radians(args[0])
functions[(1, 'radians')] = _radians
def _random(args):
return random.random()
functions[(0, 'random')] = _random
def _random2(args):
return random.uniform(args[0], args[1])
functions[(2, 'random')] = _random2
def _randomint(args):
return random.randint(args[0], args[1])
functions[(2, 'randomint')] = _randomint
def _sin(args):
return math.sin(args[0])
functions[(1, 'sin')] = _sin
def _sqrt(args):
if args[0] < 0:
raise ThresholdError("Imaginary numbers suck. For seriously.")
return math.sqrt(args[0])
functions[(1, 'sqrt')] = _sqrt
def _sum(args):
if abs(args[1] - args[0]) > 999999:
raise ThresholdError("Sums with over one million possible steps aren't supported.")
if len(args) == 2:
return sum(range(args[0], args[1] + 1))
if args[2] == 0:
raise ThresholdError("A sum with a step of 0 will not resolve.")
dest = args[1]
if args[2] < 0:
dest -= 1
else:
dest += 1
return sum(range(args[0], dest, args[2]))
functions[(2, 'sum')] = _sum
functions[(3, 'sum')] = _sum
def _tan(args):
return math.tan(args[0])
functions[(1, 'tan')] = _tan
return functions
_FUNCTIONS = _generateBuiltinFunctions() #: Pre-defined functions.
del _generateBuiltinFunctions #Remove the no-longer-necessary generator.
#Calculator logic
########################################
def _preprocessIdentifier(identifier):
if identifier[0] == '`':
return identifier[1:-1]
return identifier
def _parseLine(raw_line):
"""
This function serves as the calculator's lexer, taking an input string and
converting it into tokens.
This function does not employ any syntaxtic or semantic processing. Rather,
it just scans the entire string in linear fashion and generates a list of
tokens that represent the content it received.
It works by first determining which type of expression it is processing,
extracting any meta-data (such as name and parameters), and then lexing the
body of the expression.
While lexing, it successively applies the following logic to the remaining
string::
- Drop leading whitespace
- Break if nothing is left
- Lex token::
- If numeric, parse and add
- If a function, add a symbolic reference
- If a variable, add a symbolic reference
- If any other valid character, add directly
@type raw_line: basestring
@param raw_line: The string to be lexed.
@rtype: (list, int)
@return: A list of all tokens lexed from the input string and a _LINE
constant that indicates the type of expression parsed.
@raise IllegalCharacterError: If an invalid character is found.
"""
line = raw_line.strip()
tokens = []
match = _LINE_FUNCTION_REGEXP.match(line)
if match:
line_type = _LINE_FUNCTION
tokens.append(_preprocessIdentifier(match.group(1))) #Add the name.
tokens.append(match.group(2)) #Add the parameters.
line = match.group(3)
else:
match = _LINE_VARIABLE_REGEXP.match(line)
if match:
line_type = _LINE_VARIABLE
tokens.append(_preprocessIdentifier(match.group(1))) #Add the name.
line = match.group(2)
else:
line_type = _LINE_EQUATION
tokens += _splitLine(line, raw_line)
return (tokens, line_type)
def _splitLine(line, raw_line):
tokens = []
while True:
line = line.lstrip()
if not line:
break
match = _NUMERIC_REGEXP.match(line)
if match:
number = match.group(1)
if number.find('.') == -1:
tokens.append(int(number))
else:
tokens.append(float(number))
else:
match = _FUNCTION_REGEXP.match(line)
if match:
tokens.append("%s:%s" % (_FUNCTION_PREFIX, _preprocessIdentifier(match.group(1))))
tokens.append('(')
else:
match = _VARIABLE_REGEXP.match(line)
if match:
tokens.append("%s:%s" % (_VARIABLE_PREFIX, _preprocessIdentifier(match.group(1))))
else:
if line[0] in _ALLOWED_TOKENS:
tokens.append(line[0])
else:
raise IllegalCharacterError(raw_line, line[0])
if match:
line = line[match.end():]
else:
line = line[1:]
return tokens
def _validateExpression(raw_tokens, functions, variables):
"""
This function performs a semantic check on an expression to make sure that
it should be computable. At the same time, it compiles symbolic links.
Additionally, through _validateSyntax(), it performs a syntax check.
It works by replacing symbolic references to variables and functions with
actual objects. Upon completion, syntax validation is performed.
Nested expressions, such as those passed as arguments to functions, are
recursively validated.
This function returns a list containing a compiled version of the initial
input.
@type raw_tokens: list
@param raw_tokens: The tokenized expression to be validated.
@type functions: defaultdict
@param functions: A dictionary of functions, keyed by arity and name.
@type variables: defaultdict
@param variables: A dictionary of variables, keyed by name.
@rtype: list
@return: A compiled version of the initial input.
@raise UnterminatedFunctionError: If a function call is missing its terminal
parenthesis.
@raise UnexpectedCharacterError: If a token appears in a position where it
contradicts the syntactic structure of an expression.
@raise ConsecutiveFactorError: If two factors appear consecutively.
@raise ConsecutiveOperatorError: If two operators appear consecutively.
@raise UnbalancedParenthesesError: If the expression ends without closing
all parentheses.
@raise IncompleteExpressionError: If the expression ends while expecting a
factor.
@raise VariableError: If a variable was referenced but not found.
@raise FunctionError: If a function was referenced but not found.
@raise TokensError: If no tokens are provided for a function's parameter.
"""
tokens = raw_tokens[:]
tokens.reverse()
do_negation = True
last_variable = False
last_parenthesis = False
last_factor = False
expression = []
while tokens:
token = tokens.pop()
if isinstance(token, basestring):
if do_negation and token == '-':
expression.append(-1)
expression.append(_NEGATION_MULTIPLIER)
continue
if token[0] in _NEGATION_DISABLER:
do_negation = False
elif token in _OPERATORS:
do_negation = True
if token[0] == _VARIABLE_PREFIX:
if last_variable or last_parenthesis or last_factor:
expression.append('*')
expression.append(_validateExpression_variable(raw_tokens, token, variables))
last_parenthesis = last_factor = False
last_variable = True
elif token[0] == _FUNCTION_PREFIX:
if last_variable or last_parenthesis or last_factor:
expression.append('*')
expression.append(_validateExpression_function(raw_tokens, token, tokens, functions, variables))
last_parenthesis = last_factor = False
last_variable = True
else:
if token == '(':
if last_variable or last_factor:
expression.append('*')
last_parenthesis = last_variable = last_factor = False
elif token == ')':
last_variable = last_factor = False
last_parenthesis = True
expression.append(token)
last_parenthesis = last_variable = last_factor = False
else:
do_negation = False
if last_variable or last_parenthesis:
expression.append('*')
expression.append(token)
last_variable = last_parenthesis = False
last_factor = True
_validateSyntax(expression, raw_tokens)
return expression
def _validateSyntax(tokens, raw_tokens):
"""
This function performs the actual process of validating the syntax of an
expression.
It works by ensuring that factors and operators appear in alternating
order, with a factor on each end.
Bracketed expressions count as factors if they contain valid content.
@type tokens: list
@param tokens: The tokenized expression to be evaluated.
@type raw_tokens: list
@param raw_tokens: The original tokenized expression.
@raise UnexpectedCharacterError: If a token appears in a position where it
contradicts the syntactic structure of an expression.
@raise ConsecutiveFactorError: If two factors appear consecutively.
@raise ConsecutiveOperatorError: If two operators appear consecutively.
@raise UnbalancedParenthesesError: If the expression ends without closing
all parentheses.
@raise IncompleteExpressionError: If the expression ends while expecting a
factor.
"""
expecting_factor = True
if tokens:
tokens = tokens[:]
tokens.reverse()
else:
tokens = [0]
while tokens:
token = tokens.pop()
if isinstance(token, basestring):
if not token in _OPERATORS or token == ')':
raise UnexpectedCharacterError(token, raw_tokens)
if token == '(': #Check the subexpression.
if not expecting_factor:
raise ConsecutiveFactorError(token, raw_tokens)
depth = 1
expression = []
while tokens:
e_token = tokens.pop()
if e_token == '(':
depth += 1
elif e_token == ')':
depth -= 1
if depth == 0:
_validateSyntax(expression, raw_tokens)
break
expression.append(e_token)
if depth > 0:
raise UnbalancedParenthesesError(raw_tokens)
elif expecting_factor:
raise ConsecutiveOperatorError(token, raw_tokens)
elif not expecting_factor:
raise ConsecutiveFactorError(token, raw_tokens)
expecting_factor = not expecting_factor
if expecting_factor:
raise IncompleteExpressionError(raw_tokens)
def _validateExpression_variable(raw_tokens, token, variables):
"""
This function processes an instance of a variable within an expression's
tokens.
A compiled variable reference is returned.
@type raw_tokens: list
@param raw_tokens: The original tokenized expression being processed.
@type token: str
@param token: The string that identifies which variable is being referenced.
@type variables: defaultdict
@param variables: A dictionary of variables, keyed by name.
@rtype: None|tuple
@return: A tuple of the variable's builtin/custom status, the variable
or None if not in semantics mode.
@raise VariableError: If the named variable does not exist.
"""
identifier = token[2:]
variable = variables[identifier]
if variable is not None:
return (identifier in variables and _VARIABLE_CUSTOM or _VARIABLE_EXTERNAL, variable)
variable = _VARIABLES.get(identifier) #Look for a builtin variable.
if variable is not None:
return variable
raise VariableError(identifier, raw_tokens)
def _validateExpression_function(raw_tokens, token, tokens, functions, variables):
"""
This function processes an instance of a function within an expression's
tokens.
A compiled function reference is returned.
@type raw_tokens: list
@param raw_tokens: The original tokenized expression being processed.
@type token: str
@param token: The string that identifies which function is being referenced.
@type tokens: list
@param tokens: The tokens remaining in the expression, starting from the
opening parenthesis of the function's parameter list.
@type functions: defaultdict
@param functions: A dictionary of functions, keyed by arity and name.
@type variables: defaultdict
@param variables: A dictionary of variables, keyed by name.
@rtype: None|tuple
@return: A tuple of the function's builtin/custom status, the function
object, and the function's arguments (a tuple of equations) or None if
not in semantics mode.
@raise TokensError: If no tokens are provided.
@raise UnterminatedFunctionError: If a function call is missing its terminal
parenthesis.
@raise UnexpectedCharacterError: If a token appears in a position where it
contradicts the syntactic structure of an expression.
@raise ConsecutiveFactorError: If two factors appear consecutively.
@raise ConsecutiveOperatorError: If two operators appear consecutively.
@raise UnbalancedParenthesesError: If the expression ends without closing
all parentheses.
@raise IncompleteExpressionError: If the expression ends while expecting a
factor.
@raise FunctionError: If the named function does not exist.
"""
identifier = token[2:]
parameters = _validateExpression_parameters(raw_tokens, tokens, identifier, functions, variables)
arity = len(parameters)
spec = (arity, identifier)
function = functions[spec]
if function is not None:
return (spec in functions and _FUNCTION_CUSTOM or _FUNCTION_EXTERNAL, function, parameters)
function = _FUNCTIONS.get(spec)
if function is not None:
return (_FUNCTION_BUILTIN, function, parameters)
raise FunctionError(identifier, arity, tokens)
def _validateExpression_parameters(raw_tokens, tokens, function_name, functions, variables):
"""
This function takes an expression from the start of a function's
argument list and generates or validates equations for each argument to be
passed.
A compiled collection of parameters is returned.
@type raw_tokens: list
@param raw_tokens: The original tokenized expression being processed.
@type tokens: list
@param tokens: The tokenized expression being processed.
@type function_name: str
@param function_name: The name of the function for which parameters are
being processed.
@type functions: defaultdict
@param functions: A dictionary of functions, keyed by arity and name.
@type variables: defaultdict
@param variables: A dictionary of variables, keyed by name.
@rtype: None|tuple
@return: A tuple of all equations that will serve as function parameters or
None if not in semantics mode.
@raise TokensError: If no tokens are provided.
@raise UnterminatedFunctionError: If a function call is missing its terminal
parenthesis.
@raise UnexpectedCharacterError: If a token appears in a position where it
contradicts the syntactic structure of an expression.
@raise ConsecutiveFactorError: If two factors appear consecutively.
@raise ConsecutiveOperatorError: If two operators appear consecutively.
@raise UnbalancedParenthesesError: If the expression ends without closing
all parentheses.
@raise IncompleteExpressionError: If the expression ends while expecting a
factor.
"""
depth = 1
parameter = []
parameters = []
tokens.pop() #Drop the opening parenthesis.
while tokens:
token = tokens.pop()
if token == '(':
depth += 1
elif token == ')':
depth -= 1
if depth == 0:
if parameter or parameters: #Allow for 0-arity.
equation = Equation(parameter)
equation.compile(functions, variables)
parameters.append(equation)
break
elif depth == 1 and token == _FUNCTION_DELIMITER:
equation = Equation(parameter)
equation.compile(functions, variables)
parameters.append(equation)
parameter = []
continue
parameter.append(token)
if depth > 0:
raise UnterminatedFunctionError(function_name, raw_tokens)
return tuple(parameters)
def _convertRPN(tokens):
"""
This function converts a valid expression into an RPN token stack.
@type tokens: list
@param tokens: The tokenized expression to be converted.
@rtype: list
@return: An RPN token stack representing the given expression.
@raise UnbalancedParenthesesError: If the expression ends without closing
all parentheses.
"""
rpn_tokens = []
stack = []
sum = 0
for i in tokens:
if not i in _OPERATORS:
rpn_tokens.append(i)
else:
if i == '(':
stack.append(i)
elif i == ')':
match_found = False
while stack:
token = stack.pop()
if token == '(':
match_found = True
break
else:
rpn_tokens.append(token)
if not match_found:
raise UnbalancedParenthesesError(tokens)
else:
while stack:
if _OPERATOR_PRECEDENCE[i] <= _OPERATOR_PRECEDENCE[stack[-1]]:
rpn_tokens.append(stack.pop())
else:
break
stack.append(i)
while stack:
token = stack.pop()
if token == '(':
raise UnbalancedParenthesesError(tokens)
rpn_tokens.append(token)
return rpn_tokens
def _evaluateRPN(tokens, call_stack):
"""
This function evaluates an RPN-i-fied expression.
Each factor in the token stack is individually evaluated to ensure that
function and variable values are computed only when needed.
@type tokens: list
@param tokens: The RPN stack to evaluate.
@type call_stack: list
@param call_stack: A stack containing every function and variable traversed
up to this point.
@rtype: int|float
@return: The result of the evaluation.
@raise ThresholdError: If the values passed to an operand or function exceed
pre-defined limits.
@raise DivisionByZeroError: If a division by zero would occur as a result of
an operation.
@raise IncompleteExpressionError: If there are excessive tokens in the input
stack.
@raise NullSubexpressionError: If a bracketed expression contains no
content.
"""
stack = []
for i in tokens:
if i in _PURE_OPERATORS:
token_right = stack.pop()
token_left = stack.pop()
value_right = _evaluate(token_right, call_stack)
value_left = _evaluate(token_left, call_stack)
if i == '^':
if value_left > 9999999 or value_right > 1024:
raise ThresholdError("The time required to calculate such a power is too great.")
stack.append(value_left ** value_right)
elif i in ('*', _NEGATION_MULTIPLIER):
stack.append(value_left * value_right)
elif i == '/':
if value_right == 0:
raise DivisionByZeroError(token_left, token_right, ['RPN:'] + tokens)
stack.append(value_left / float(value_right))
elif i == '\\':
if value_right == 0:
raise DivisionByZeroError(token_left, token_right, ['RPN:'] + tokens)
stack.append(int(value_left // value_right))
elif i == '%':
stack.append(value_left % value_right)
elif i == '+':
stack.append(value_left + value_right)
elif i == '-':
stack.append(value_left - value_right)
elif i == '<':
stack.append(min(value_left, value_right))
elif i == '>':
stack.append(max(value_left, value_right))
else:
stack.append(_evaluate(i, call_stack))
if len(stack) > 1:
raise IncompleteExpressionError(['RPN:'] + tokens)
if len(stack) < 1:
raise NullSubexpressionError()
return stack[0]
def _evaluate(token, call_stack):
"""
This function evaluates a token to provide a value processable by the
computation mechanism.
@type token: int|float|tuple
@param token: The token to evaluate.
@type call_stack: list
@param call_stack: A stack containing every function and variable traversed
up to this point.
@rtype: int|float
@return: The value of the token.
"""
if type(token) == tuple:
if token[0] == _VARIABLE_CUSTOM:
return token[1].evaluate(call_stack)
elif token[0] in (_VARIABLE_BUILTIN, _VARIABLE_EXTERNAL):
return token[1]
elif token[0] == _FUNCTION_CUSTOM:
return token[1].evaluate(token[2], call_stack)
elif token[0] == _FUNCTION_BUILTIN:
return token[1]([i.evaluate(call_stack) for i in token[2]])
elif token[0] == _FUNCTION_EXTERNAL:
return token[1].evaluate([i.evaluate(call_stack) for i in token[2]], call_stack)
else:
raise UnknownTypeError(token)
return token
def _renderExpression(tokens):
"""
This function provides a mostly-sane, human-readable rendition of the tokens
that make up an expression processed by the lexer.
@type tokens: list
@param tokens: The expression to render
@rtype: str
@return: A rendition of the expression.
"""
buffer = []
pad = False
pad_character = ' '
for i in tokens:
if pad and not i in (')', _FUNCTION_DELIMITER):
buffer.append(pad_character)
if isinstance(i, basestring):
if i[0] == _FUNCTION_PREFIX:
i = i[2:]
pad = False
elif i[0] == _VARIABLE_PREFIX:
i = i[2:]
pad = True
elif i == '-':
if len(buffer) >= 2 and buffer[-1] == pad_character and buffer[-2] in _PURE_OPERATORS:
pad = False
else:
pad = not i == '('
else:
if type(i) == tuple:
if i[0] in (_VARIABLE_CUSTOM, _VARIABLE_EXTERNAL, _VARIABLE_BUILTIN, _FUNCTION_CUSTOM, _FUNCTION_EXTERNAL):
i = i[1]
elif i[0] == _FUNCTION_BUILTIN:
i = "%s(%s)" % (i[1].__name__[1:] + ", ".join([str(parameter) for parameter in i[2]]))
pad = True
buffer.append(str(i))
return ''.join(buffer)
#Logical entities
########################################
class Equation(object):
"""
This class models an equation, which is any expression that can be evaluated
to produce a numeric value.
"""
_tokens = None #: The tokens that make up this expression.
_equation = None #: The expression to be evaluated in RPN, with substitutions.
def __init__(self, tokens):
"""
This constructs a new Equation.
@type tokens: list
@param tokens: A list of tokens that represent the expression modeled by
this equation.
@raise TokensError: If no tokens are provided.
@raise UnterminatedFunctionError: If a function call is missing its terminal
parenthesis.
@raise UnexpectedCharacterError: If a token appears in a position where it
contradicts the syntactic structure of an expression.
@raise ConsecutiveFactorError: If two factors appear consecutively.
@raise ConsecutiveOperatorError: If two operators appear consecutively.
@raise UnbalancedParenthesesError: If the expression ends without closing
all parentheses.
@raise IncompleteExpressionError: If the expression ends while expecting a
factor.
"""
if not tokens:
raise TokensError()
self._tokens = tokens
def copy(self):
"""
Returns a non-compiled copy.
"""
return Equation(self._tokens)
def compile(self, functions, variables):
"""
This function compiles this equation, performing semantic validation and
replacing symbolic function and variable references with object-based
ones.
When done, this equation will be ready for evaluation.
@type functions: defaultdict
@param functions: A dictionary of functions, keyed by arity and name.
@type variables: defaultdict
@param variables: A dictionary of variables, keyed by name.
@raise TokensError: If no tokens are provided.
@raise UnterminatedFunctionError: If a function call is missing its terminal
parenthesis.
@raise UnexpectedCharacterError: If a token appears in a position where it
contradicts the syntactic structure of an expression.
@raise ConsecutiveFactorError: If two factors appear consecutively.
@raise ConsecutiveOperatorError: If two operators appear consecutively.
@raise UnbalancedParenthesesError: If the expression ends without closing
all parentheses.
@raise IncompleteExpressionError: If the expression ends while expecting a
factor.
"""
if self._equation: #Already compiled.
return
if not self._tokens:
raise TokensError()
self._equation = _convertRPN(_validateExpression(self._tokens, functions, variables))
def evaluate(self, stack=None):
"""
This function provides the numeric value of this equation.
@type stack: None|list
@param stack: A stack containing every function and variable traversed
until this point.
@rtype: int|float
@return: The value of this equation.
@raise CompilationError: If this equation has not been compiled.
@raise RecursionError: If this equation has already been invoked during
the evaluation process.
@raise ThresholdError: If the values passed to an operand or function exceed
pre-defined limits.
@raise DivisionByZeroError: If a division by zero would occur as a result of
an operation.
@raise IncompleteExpressionError: If there are excessive tokens in the input
stack.
@raise NullSubexpressionError: If a bracketed expression contains no
content.
"""
if self._equation == None:
raise CompilationError(self._tokens)
if not stack:
stack = []
elif self in stack:
raise RecursionError(stack + [self])
stack.append(self)
return _evaluateRPN(self._equation, stack[:])
def getTokens(self):
return self._tokens
def getRPNTokens(self):
return self._equation
def __str__(self):
return _renderExpression(self._tokens)
class Variable(Equation):
"""
This class models a variable, which is an equation that stores a value for
later (re-)use.
"""
_name = None #: The name of this variable.
_computed_value = None #: The pre-computed value of this variable.
def __init__(self, tokens, name):
"""
This constructs a new Variable.
@type tokens: list
@param tokens: A list of tokens that represent the expression modeled by
this variable.
@type name: basestring
@param name: The name of this variable.
@raise TokensError: If no tokens are provided.
@raise UnterminatedFunctionError: If a function call is missing its terminal
parenthesis.
@raise UnexpectedCharacterError: If a token appears in a position where it
contradicts the syntactic structure of an expression.
@raise ConsecutiveFactorError: If two factors appear consecutively.
@raise ConsecutiveOperatorError: If two operators appear consecutively.
@raise UnbalancedParenthesesError: If the expression ends without closing
all parentheses.
@raise IncompleteExpressionError: If the expression ends while expecting a
factor.
"""
Equation.__init__(self, tokens)
self._name = name
def copy(self):
"""
Returns a non-compiled copy.
"""
return Variable(self._tokens, self._name)
def compute(self, stack=None):
"""
This function pre-computes the value of this variable, preventing
redundant when it will be used repeatedly. This function should be
invoked only when beginning a batch of equations, and it should be
followed by a call to reset().
@type stack: list
@param stack: A stack containing every function and variable traversed
until this point.
@raise CompilationError: If this equation has not been compiled.
@raise RecursionError: If this equation has already been invoked during
the evaluation process.
@raise ThresholdError: If the values passed to an operand or function exceed
pre-defined limits.
@raise DivisionByZeroError: If a division by zero would occur as a result of
an operation.
@raise IncompleteExpressionError: If there are excessive tokens in the input
stack.
@raise NullSubexpressionError: If a bracketed expression contains no