Recently we came across requirement where we need to evaluate/compare/validate the algebra equation.
Different ways to do it -
- Use eval() function of python
>>> x = 2
>>> eval("x+2")
4
- Use Regex - Not a practical approach
- Use Sympy - works for simple cases which we are interested in, though probably we are just using the <10% of it.
>>> from sympy import *
>>> x = Symbol('x')
>>> y = Symbol('y')
>>> simplify(2*x+y)
2*x + y
>>> simplify(y+2*x)
2*x + y
p.s. both 2x+y and y+2x is same thing.
>>> simplify(2*(x+7)) == simplify(2*x + 14)
True
>>> simplify(2*(x+7)) == simplify(2*x + 13)
False
>>> simplify(2*(y+7)) == simplify(2*x + 14)
False
>>> simplify(2*(y+7)) == simplify(2*y + 14)
True
10>
Because in python if you specify 1/2, the answer is 0 as it consider it as positive integer, to get the decimal points you need to use 1.0/2.0
It can do expand the equation for you too -
>>> expand((x+y)**6)
x**6 + 6*x**5*y + 15*x**4*y**2 + 20*x**3*y**3 + 15*x**2*y**4 + 6*x*y**5 + y**6
For more information you can checkout here.
Different ways to do it -
- Use eval() function of python
>>> x = 2
>>> eval("x+2")
4
- Use Regex - Not a practical approach
- Use Sympy - works for simple cases which we are interested in, though probably we are just using the <10% of it.
>>> from sympy import *
>>> x = Symbol('x')
>>> y = Symbol('y')
>>> simplify(2*x+y)
2*x + y
>>> simplify(y+2*x)
2*x + y
p.s. both 2x+y and y+2x is same thing.
>>> simplify(2*(x+7)) == simplify(2*x + 14)
True
>>> simplify(2*(x+7)) == simplify(2*x + 13)
False
>>> simplify(2*(y+7)) == simplify(2*x + 14)
False
>>> simplify(2*(y+7)) == simplify(2*y + 14)
True
10>
Here is the interesting one though -
>>> simplify((1/2) * 7*x) == simplify(7*x / 2)
False
>>> simplify(0.5 * 7*x) == simplify(7*x / 2)
True
>>> simplify((1.0/2.0) * 7*x) == simplify(7*x / 2)
True
Because in python if you specify 1/2, the answer is 0 as it consider it as positive integer, to get the decimal points you need to use 1.0/2.0
It can do expand the equation for you too -
>>> expand((x+y)**6)
x**6 + 6*x**5*y + 15*x**4*y**2 + 20*x**3*y**3 + 15*x**2*y**4 + 6*x*y**5 + y**6
For more information you can checkout here.
No comments:
Post a Comment