From string to sympy expression

余生颓废 提交于 2019-12-10 21:11:15

问题


Recently I was working on a web application, using Flask and sympy libraries. The user enters his equation in a textarea and Flask rechieve it as a string. I would like to have the possibility to calculate the result of this equation,by using sympy function solve(). But for this I must convert this string to an sympy expression. How could I do that?

`

from flask import Flask,request,render_template,flash
from sympy import *
from sympy.parsing.sympy_parser import *

x = symbols('x')
app = Flask(__name__)
app.secret_key = 'mysecretkey'


def calculate_():
    first_eq = request.form['first_eq']

    first_eq2= parse_expr(first_eq)
    result = solve(first_eq2)
    return result


@app.route("/",methods=['GET', 'POST'])
def myGet():

    return render_template("my-form.html")

@app.route("/myPost/",methods=['GET', 'POST'])
def myPost():
    answer = request.form['answer']
    result_of_answer=solve(Eq(answer),x)
    result = calculate_()
    try:
        if result == result_of_answer:
            flash("you got it!")
        else:
            flash("no, it's wrong")
            return render_template("my-form.html")
    except:
        flash("sorry, wrong type. Try again!")
        return render_template("my-form.html")
if __name__ == '__main__':
    app.run()`

回答1:


The function you're looking for is sympify. http://docs.sympy.org/latest/modules/core.html#sympy.core.sympify.sympify



来源:https://stackoverflow.com/questions/33606667/from-string-to-sympy-expression

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