简体   繁体   中英

integration and differentiation with sympy/pyqt python

I'm creating a system which quizes the user on integration and differentiation using python 3. when i display questions they are in a form like:

-25*x**(3/5)/3 + 6*x**(4/3) - 5*x**6/3 + x**2/2 - 4*x

How could I change it to a form like:

-25x^(3/5)/3 + 6x^(4/3) - 5x^6/3 + x^2/2 - 4x

Also I want it so when users type in equivalent answers it is still recognised

For simple display replacement you could use:

def format_math(string):
    return (string.replace("**", "^")).replace("*", "")

Then you could use it versus user input to compare their input answer versus yours.

 x = format_math("-25*x**(3/5)/3 + 6*x**(4/3) - 5*x**6/3 + x**2/2 - 4*x")
 # -25x^(3/5)/3 + 6x^(4/3) - 5x^6/3 + x^2/2 - 4x
 user_input = format_math(input("Enter your answer: "))
 # If the user enters # -25x^(3/5)/3 + 6x^(4/3) - 5x^6/3 + x^2/2 - 4x or
 # -25*x**(3/5)/3 + 6*x**(4/3) - 5*x**6/3 + x**2/2 - 4*x the program will 
 # recognize both as correct
 if x == user_input:
     return True

From the python docs:

If the intention is to use sympy , then the following will work:

import sympy as sp
x = sp.symbols('x')
sp.init_printing()

y = -25*x**(sp.Integer(3)/sp.Integer(5)
    )/sp.Integer(3) + 6*x**(sp.Integer(4)/sp.Integer(3)
    ) - sp.Integer(5)*x**sp.Integer(6)/sp.Integer(3) + x**sp.Integer(
    2)/sp.Integer(2) - 4*x

y

SymPy表达

Expressions can then be simplified and compared using sympy 's tools. If it was preferable to not use sp.Integer() explicitly to prevent Python from doing the divisions, one could substitute it into the original expression string using regular expressions before using sp.sympify() to convert the string into a SymPy expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM