coding utf-8 from pyparsing import Literal CaselessLiteral Word Combin

 ``` 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``` ```# -*- coding: utf-8 -*- from pyparsing import Literal,CaselessLiteral,Word,Combine,Group,Optional,\ ZeroOrMore,Forward,nums,alphas,ParseException import math import operator exprStack = [] def pushFirst( strg, loc, toks ): exprStack.append( toks[0] ) def pushUMinus( strg, loc, toks ): if toks and toks[0]=='-': exprStack.append( 'unary -' ) #~ exprStack.append( '-1' ) #~ exprStack.append( '*' ) def inc(a): if type(a) is float: return a+1 raise Exception('MyException', 'MyException') def dec(a): if type(a) is float: return a-1 raise Exception('MyException', 'MyException') def logical_not(a): """Logical not""" if a is "F": return "T" if a is "T": return "F" raise Exception('MyException', 'MyException') def lgc_equal(a,b): if lgc_nequal(a,b) == "T": return "F" else: return "T" def lgc_nequal(a,b): """Logical !=""" try: x = float(a) y = float(b) except ValueError: if a!=b: return "T" if a==b: return "F" raise Exception('MyException', 'MyException') if x!=y: return "T" if x==y: return "F" raise Exception('MyException', 'MyException') def lgc_nmore(a,b): """Logical <=""" if type(a) is float and type(b) is float: if a<=b: return "T" else: return "F" raise Exception('MyException', 'MyException') def lgc_nless(a,b): """Logical >=""" if type(a) is float and type(b) is float: if a>=b: return "T" else: return "F" raise Exception('MyException', 'MyException') bnf = None def BNF(): """ expop :: '^' multop :: '*' | '/' addop :: '+' | '-' integer :: ['+' | '-'] '0'..'9'+ atom :: PI | E | real | fn '(' expr ')' | '(' expr ')' factor :: atom [ expop factor ]* term :: factor [ multop factor ]* expr :: term [ addop term ]* lgc :: expr [ logicalop expr]* """ global bnf if not bnf: point = Literal( "." ) e = CaselessLiteral( "E" ) fnumber = Combine( Word( "+-"+nums, nums ) + Optional( point + Optional( Word( nums ) ) ) + Optional( e + Word( "+-"+nums, nums ) ) ) T = CaselessLiteral("T") F = CaselessLiteral("F") ident = Word(alphas, alphas+nums+"_\$") #ident = CaselessLiteral("not") plus = Literal( "+" ) minus = Literal( "-" ) mult = Literal( "*" ) div = Literal( "/" ) lpar = Literal( "(" ).suppress() rpar = Literal( ")" ).suppress() pmod = CaselessLiteral( "mod" ) pdiv = CaselessLiteral( "div" ) nbiger = Literal( "<=" ) nless = Literal( ">=" ) nequal = Literal( "<>" ) equal = Literal( "=" ) addop = plus | minus multop = mult | div | pmod | pdiv logicalop = nbiger | nless | nequal | equal expop = Literal( "^" ) pi = CaselessLiteral( "PI" ) expr = Forward() lgc = Forward() atom = (Optional("-") + ( pi | e | fnumber | T | F | ident + lpar + lgc + rpar | ident + lpar + expr + rpar ).setParseAction( pushFirst ) | ( lpar + lgc.suppress() + rpar ) | ( lpar + expr.suppress() + rpar )).setParseAction(pushUMinus) # by defining exponentiation as "atom [ ^ factor ]..." instead of "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-righ # that is, 2^3^2 = 2^(3^2), not (2^3)^2. factor = Forward() factor << atom + ZeroOrMore( ( expop + factor ).setParseAction( pushFirst ) ) term = factor + ZeroOrMore( ( multop + factor ).setParseAction( pushFirst ) ) expr << term + ZeroOrMore( ( addop + term ).setParseAction( pushFirst ) ) lgc << expr + ZeroOrMore( ( logicalop + expr ).setParseAction(pushFirst) ) bnf = lgc return bnf # map operator symbols to corresponding arithmetic operations epsilon = 1e-12 opn = { "+" : operator.add, "-" : operator.sub, "*" : operator.mul, "/" : operator.truediv, "^" : operator.pow, "div": operator.floordiv, "mod": operator.mod, "<=" : lgc_nmore, ">=" : lgc_nless, "<>" : lgc_nequal, "=" : lgc_equal } fn = { "not" : logical_not, "inc" : inc, "dec" : dec, "sin" : math.sin, "cos" : math.cos, "tan" : math.tan, "abs" : abs, "trunc" : lambda a: int(a), "round" : round, "sgn" : lambda a: abs(a)>epsilon and cmp(a,0) or 0} def evaluateStack( s ): op = s.pop() if op == 'unary -': return -evaluateStack( s ) if op in opn.keys(): #"+-*/^" or op is "mod" or op is "div": op2 = evaluateStack( s ) op1 = evaluateStack( s ) try: return opn[op]( op1, op2 ) except TypeError: raise Exception('MyException', 'MyException') elif op == "PI": return math.pi # 3.1415926535 elif op == "E": return math.e # 2.718281828 elif op in fn: return fn[op]( evaluateStack( s ) ) elif op is "T" or op is "F": return op elif op[0].isalpha(): raise Exception('MyException', 'MyException') else: try: return float( op ) except ValueError: raise Exception('MyException', 'MyException') def parse(s): for op in opn.keys(): l = len(op) if l>len(s): continue if (op == s[:l] and op not in ["-", "+"]) or op == s[-l]: raise Exception('MyException', 'MyException') BNF().parseString( s ) print exprStack val = evaluateStack( exprStack ) return val # try: # for op in opn.keys(): # l = len(op) # if l>len(s): # continue # if (op == s[:l] and op not in ["-", "+"]) or op == s[-l]: # return "Перевірте правильність виразу" # # BNF().parseString( s ) # val = evaluateStack( exprStack ) # except ParseException as e: # return "Помилка бiля сымволу №"+str(e.loc+1) # except: # return "Перевірте правильність виразу" # return val if __name__ == "__main__": def test( s, expVal ): global exprStack exprStack = [] results = BNF().parseString( s ) val = evaluateStack( exprStack[:] ) print '"'+s+'"'+' ==',val,' => ', results, ' => ', exprStack #if val == expVal: #print s, "=", val, results, "=>", exprStack #else: # print s+"!!!", val, "!=", expVal, results, "=>", exprStack #test("dec(7^1)^", 0) #T<>(7<>8)<>T print parse("123-1") ```