This python code is not solving equations

心已入冬 提交于 2021-02-11 12:02:58

问题


I have a chat bot for an Instant messenger and I am trying to make a math solver for it but it can't send the solution of equation to the Instant messenger, it sends equation instead.

If someone from Instant messenger sends "solve: 2+2", this program should send them "4" not "2+2".

Main problem:

if (parser.getPayload().lower()[:6]=="solve:"):
                    parser.sendGroupMessage(parser.getTargetID(), str(parser.getPayload()[7:]))

output:

it's sending same input again not the answer of equation

Test: I tested something and that's working properly. If I add this code, program will send solution of equation:

if (parser.getPayload().lower()=="test"):
                    parser.sendGroupMessage(parser.getTargetID(), str(2 + 2 -3 + 8 * 7))

Output: Working perfectly


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/39908815/this-python-code-is-not-solving-equations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!