This Python Code Is Not Solving Equations
Solution 1:
Your test code
str(2 + 2 -3 + 8 * 7)
is distinct from your production code
str(parser.getPayload()[7:])
which gets expanded into
str("2 + 2 -3 + 8 * 7")
assuming you pass in the same equotation. Good thing is you have the plumbing working, now you need to implement the actual math solver like
str(solve_math(parser.getPayload()[7:]))
def solve_math(expr : str) -> float:
"""
Parses and evaluates math expression `expr` and returns its result.
"""
Here you need to first parse the expression string into some structure representing the data, the operators / functions and the evaluation order. So your "2 + 2" expression gets turned into something like Addition(Const(2), Const(2))
while expression "2 + 2 * 3" gets turned into somethng like Addition(Const(2), Multiplication(Const(2), Const(3)))
and then you need to just evaluate it which should be fairly simple.
I recommend pyparsing
to help you with that.
Solution 2:
What you need to do this evaluating math expressions in string form.
However, user inputs are dangerous if you are just eval
things whatever they give you. Security of Python's eval() on untrusted strings?
You can use ast.literal_eval
to lower the risk.
Or you can use a evaluator from answers of following question Evaluating a mathematical expression in a string
Post a Comment for "This Python Code Is Not Solving Equations"