Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import operator
- class ParseError(Exception):
- pass
- op = {'+': (0, operator.add),
- '-': (0, operator.sub),
- '*': (1, operator.mul),
- '/': (1, operator.truediv),
- '^': (2, operator.pow)}
- def parcheck(s):
- c = 0
- for t in s:
- c += (t=="(") -(t==")")
- if c<0:
- return False
- return c == 0
- def parse(s):
- if not s:
- return 0
- if s[0] == "(" and s[-1]==")":
- if parcheck(s[1:-1]):
- return parse(s[1:-1])
- if s[0] in "*/^" or s[-1] in op:
- raise ParseError("Syntax error")
- if any(t in op for t in s):
- m = mi = -1
- c = 0
- for i, t in enumerate(s):
- if t in "()":
- c += (t=="(") - (t==")")
- elif t in op:
- if i and t in "+-" and s[i-1] in op:
- continue
- if op[t][0] + c*3 <= m or m<0:
- m, mi = op[t][0] + c*3, i
- lv, rv = parse(s[:mi]), parse(s[mi+1:])
- return op[s[mi]][1](lv, rv)
- if s[0] == "(":
- return parse(s[1:])
- if s[-1] == ")":
- return parse(s[:-1])
- try:
- return int(s)
- except:
- raise ParseError("Syntax error")
- def calc(s):
- try:
- if parcheck(s):
- if any(t.isdigit() for t in s) and s.find("()")<0:
- print(parse(s))
- else:
- raise ParseError("Syntax error")
- else:
- raise ParseError("Parentheses mismatch")
- except ParseError as e:
- print(e)
- return
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement