File: eval_arith.py

package info (click to toggle)
pyparsing 1.5.6%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 8,220 kB
  • sloc: python: 13,752; makefile: 33; sh: 17
file content (198 lines) | stat: -rw-r--r-- 6,272 bytes parent folder | download | duplicates (2)
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
# eval_arith.py
#
# Copyright 2009, Paul McGuire
#
# Expansion on the pyparsing example simpleArith.py, to include evaluation
# of the parsed tokens.
#
from pyparsing import Word, nums, alphas, Combine, oneOf, \
    opAssoc, operatorPrecedence

class EvalConstant(object):
    "Class to evaluate a parsed constant or variable"
    vars_ = {}
    def __init__(self, tokens):
        self.value = tokens[0]
    def eval(self):
        if self.value in EvalConstant.vars_:
            return EvalConstant.vars_[self.value]
        else:
            return float(self.value)

class EvalSignOp(object):
    "Class to evaluate expressions with a leading + or - sign"
    def __init__(self, tokens):
        self.sign, self.value = tokens[0]
    def eval(self):
        mult = {'+':1, '-':-1}[self.sign]
        return mult * self.value.eval()

def operatorOperands(tokenlist):
    "generator to extract operators and operands in pairs"
    it = iter(tokenlist)
    while 1:
        try:
            yield (it.next(), it.next())
        except StopIteration:
            break
            
class EvalMultOp(object):
    "Class to evaluate multiplication and division expressions"
    def __init__(self, tokens):
        self.value = tokens[0]
    def eval(self):
        prod = self.value[0].eval()
        for op,val in operatorOperands(self.value[1:]):
            if op == '*':
                prod *= val.eval()
            if op == '/':
                prod /= val.eval()
        return prod
    
class EvalAddOp(object):
    "Class to evaluate addition and subtraction expressions"
    def __init__(self, tokens):
        self.value = tokens[0]
    def eval(self):
        sum = self.value[0].eval()
        for op,val in operatorOperands(self.value[1:]):
            if op == '+':
                sum += val.eval()
            if op == '-':
                sum -= val.eval()
        return sum

class EvalComparisonOp(object):
    "Class to evaluate comparison expressions"
    opMap = {
        "<" : lambda a,b : a < b,
        "<=" : lambda a,b : a <= b,
        ">" : lambda a,b : a > b,
        ">=" : lambda a,b : a >= b,
        "!=" : lambda a,b : a != b,
        "=" : lambda a,b : a == b,
        "LT" : lambda a,b : a < b,
        "LE" : lambda a,b : a <= b,
        "GT" : lambda a,b : a > b,
        "GE" : lambda a,b : a >= b,
        "NE" : lambda a,b : a != b,
        "EQ" : lambda a,b : a == b,
        "<>" : lambda a,b : a != b,
        }
    def __init__(self, tokens):
        self.value = tokens[0]
    def eval(self):
        val1 = self.value[0].eval()
        for op,val in operatorOperands(self.value[1:]):
            fn = EvalComparisonOp.opMap[op]
            val2 = val.eval()
            if not fn(val1,val2):
                break
            val1 = val2
        else:
            return True
        return False
    

# define the parser
integer = Word(nums)
real = Combine(Word(nums) + "." + Word(nums))
variable = Word(alphas,exact=1)
operand = real | integer | variable

signop = oneOf('+ -')
multop = oneOf('* /')
plusop = oneOf('+ -')

# use parse actions to attach EvalXXX constructors to sub-expressions
operand.setParseAction(EvalConstant)
arith_expr = operatorPrecedence(operand,
    [
     (signop, 1, opAssoc.RIGHT, EvalSignOp),
     (multop, 2, opAssoc.LEFT, EvalMultOp),
     (plusop, 2, opAssoc.LEFT, EvalAddOp),
    ])

comparisonop = oneOf("< <= > >= != = <> LT GT LE GE EQ NE")
comp_expr = operatorPrecedence(arith_expr,
    [
    (comparisonop, 2, opAssoc.LEFT, EvalComparisonOp),
    ])

def main():
    # sample expressions posted on comp.lang.python, asking for advice
    # in safely evaluating them
    rules=[ 
             '( A - B ) = 0', 
             '(A + B + C + D + E + F + G + H + I) = J', 
             '(A + B + C + D + E + F + G + H) = I', 
             '(A + B + C + D + E + F) = G', 
             '(A + B + C + D + E) = (F + G + H + I + J)', 
             '(A + B + C + D + E) = (F + G + H + I)', 
             '(A + B + C + D + E) = F', 
             '(A + B + C + D) = (E + F + G + H)', 
             '(A + B + C) = (D + E + F)', 
             '(A + B) = (C + D + E + F)', 
             '(A + B) = (C + D)', 
             '(A + B) = (C - D + E - F - G + H + I + J)', 
             '(A + B) = C', 
             '(A + B) = 0', 
             '(A+B+C+D+E) = (F+G+H+I+J)', 
             '(A+B+C+D) = (E+F+G+H)', 
             '(A+B+C+D)=(E+F+G+H)', 
             '(A+B+C)=(D+E+F)', 
             '(A+B)=(C+D)', 
             '(A+B)=C', 
             '(A-B)=C', 
             '(A/(B+C))', 
             '(B/(C+D))', 
             '(G + H) = I', 
             '-0.99 LE ((A+B+C)-(D+E+F+G)) LE 0.99', 
             '-0.99 LE (A-(B+C)) LE 0.99', 
             '-1000.00 LE A LE 0.00', 
             '-5000.00 LE A LE 0.00', 
             'A < B', 
             'A < 7000', 
             'A = -(B)', 
             'A = C', 
             'A = 0', 
             'A GT 0', 
             'A GT 0.00', 
             'A GT 7.00', 
             'A LE B', 
             'A LT -1000.00', 
             'A LT -5000', 
             'A LT 0', 
             'A=(B+C+D)', 
             'A=B', 
             'I = (G + H)', 
             '0.00 LE A LE 4.00', 
             '4.00 LT A LE 7.00',
             '0.00 LE A LE 4.00 LE E > D',
         ] 
    vars_={'A': 0, 'B': 1.1, 'C': 2.2, 'D': 3.3, 'E': 4.4, 'F': 5.5, 'G': 
    6.6, 'H':7.7, 'I':8.8, 'J':9.9} 

    # define tests from given rules
    tests = []
    for t in rules:
        t_orig = t
        t = t.replace("=","==")
        t = t.replace("EQ","==")
        t = t.replace("LE","<=")
        t = t.replace("GT",">")
        t = t.replace("LT","<")
        t = t.replace("GE",">=")
        t = t.replace("LE","<=")
        t = t.replace("NE","!=")
        t = t.replace("<>","!=")
        tests.append( (t_orig,eval(t,vars_)) )

    # copy vars_ to EvalConstant lookup dict
    EvalConstant.vars_ = vars_
    for test,expected in tests:
        ret = comp_expr.parseString(test)[0]
        print test, expected, ret.eval()

if __name__=='__main__': 
    main()