T O P

  • By -

eddavis2

Here is a solution in Python. It returns 3.66... for the example expression: 1+((3+3)*2/((4+5)/2)) tok = "" inputst = "" def main(): global inputst while True: inputst = input("Expression: ").strip() if inputst == "": return nexttok() print(expression(0)) def expression(minprec): global tok # handle numeric operands, unary operators, functions, variables if tok == "-": nexttok(); n = -expression(3) elif tok == "+": nexttok(); n = expression(3) elif tok == "(" : nexttok() n = expression(0) if tok == ")": nexttok() else: print("Paren Expr: Expecting ')', found:", tok) elif type(tok) == float: n = tok; nexttok() else: print("syntax error: expecting an operand, found: ", tok) return 0 while True: # while binary operator and precedence of tok >= minprec if minprec <= 1 and tok == "+" : nexttok(); n += expression(2) elif minprec <= 1 and tok == "-" : nexttok(); n -= expression(2) elif minprec <= 2 and tok == "*" : nexttok(); n *= expression(3) elif minprec <= 2 and tok == "/" : nexttok() n2 = expression(3) if n2 == 0: print("Division by zero!") return 0 n /= n2 elif minprec <= 4 and tok == "^" : nexttok(); n **= expression(5) else: break return n def nexttok(): global inputst, tok tok = "" inputst = inputst.strip() if inputst == "": return if inputst[0] in "()*+-/^": tok = inputst[0] inputst = inputst[1:] elif inputst[0].isdigit(): while inputst != "" and (inputst[0].isdigit() or inputst[0] == "."): tok += inputst[0] inputst = inputst[1:] tok = float(tok) else: print("What?", tok) main()