Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import operator as O
- import re
- ops = {}
- ops["+"] = O.add
- ops["-"] = O.sub
- ops["*"] = O.mul
- ops["/"] = O.div
- ops["^"] = O.pow
- re_ops = "[%s]" % "\\".join([" "]+ops.keys())[1:]
- class OpIsNotSupported(Exception):
- pass
- def calc(fst, op, snd):
- print "calc, %s %s %s" % (fst, op, snd)
- if op not in ops:
- raise OpIsNotSupported(op)
- return ops[op](fst, snd)
- increment = lambda x, y: ((x or 0)*10) + int(y)
- def expr_wo_brackets(s):
- (fst, op, snd) = [None]*3
- (fstsign, sndsign) = (1, 1)
- for c in s:
- if c == "-" and op and snd is None:
- sndsign = -1
- elif c == "-" and fst is None:
- fstsign = -1
- elif '0' <= c <= '9':
- if op is None:
- fst = increment(fst, c)
- else:
- snd = increment(snd, c)
- elif re.match(re_ops, c):
- if snd is not None:
- fst = calc(fstsign * fst, op, sndsign * snd)
- op = c
- snd = None
- (fstsign, sndsign) = (1, 1)
- else:
- op = c
- else:
- raise OpIsNotSupported(c)
- return calc(fstsign * fst, op, sndsign*snd) if snd else fstsign * fst
- def validate(s):
- diff = re.sub("\d+|%s|\(|\)" % re_ops, "", s)
- if diff:
- raise OpIsNotSupported(diff[0])
- def calculator(s):
- s = s.replace("(-(", "(0-(")
- validate(s)
- while "(" in s:
- s = re.sub("\((\-?\d+(%s\-?\d+)*)\)" % re_ops, lambda m: `expr_wo_brackets(m.group(1))`, s)
- return expr_wo_brackets(s)
- print calculator("100/(8^2+6^(-(-2)))-1")
Add Comment
Please, Sign In to add comment