在Python中反转代数表达式字符串的算法

时间:2013-06-05 20:12:33

标签: python function expression sympy symbolic-math

有一种简单的方法可以使函数反转算法,例如:

>>> value = inverse("y = 2*x+3")
>>> print(value)
"x = (y-3)/2"

如果您无法为该功能制作实际代码,请向我推荐使这项工作更轻松的工具。该函数仅用于使用+, - ,*和/

进行逆算法

2 个答案:

答案 0 :(得分:6)

您应该尝试使用SymPy:

from sympy import solve
from sympy.abc import x, y

e = 2*x+3-y

solve(e,x)
#[y/2 - 3/2]
solve(e,y)
#[2*x + 3]

基于此,您可以构建inverse()之类(适用于两个变量):

def inverse(string, left_string=None):
    from sympy import solve, Symbol, sympify
    string = '-' + string
    e = sympify(string.replace('=','+'))
    if left_string:
        ans = left_string + ' = ' + str(solve(e, sympify(left_string))[0])
    else:
        left = sympify(string.split('=')[0].strip().replace('-',''))
        symbols = e.free_symbols
        symbols.remove( left )
        right = list(symbols)[0]
        ans = str(right) + ' = ' + str(solve(e, right)[0])
    return ans

示例:

inverse(' x = 4*y/2')
#'y = x/2'

inverse(' y = 100/x + x**2')
#'x = -y/(3*(sqrt(-y**3/27 + 2500) + 50)**(1/3)) - (sqrt(-y**3/27 + 2500) + 50)**(1/3)'

inverse("screeny = (isox+isoy)*29/2.0344827586206895", "isoy")
#'isoy = -isox + 0.0701545778834721*screeny'

答案 1 :(得分:3)

评论时间有点长,但这是我想到的那种事情:

import sympy

def inverse(s):
    terms = [sympy.sympify(term) for term in s.split("=")]
    eqn = sympy.Eq(*terms)
    var_to_solve_for = min(terms[1].free_symbols)
    solns = sympy.solve(eqn, var_to_solve_for)
    output_eqs = [sympy.Eq(var_to_solve_for, soln) for soln in solns]
    return output_eqs

之后我们

>>> inverse("y = 2*x+3")
[x == y/2 - 3/2]
>>> inverse("x = 100/z + z**2")
[z == -x/(3*(sqrt(-x**3/27 + 2500) + 50)**(1/3)) - (sqrt(-x**3/27 + 2500) + 50)**(1/3), z == -x/(3*(-1/2 - sqrt(3)*I/2)*(sqrt(-x**3/27 + 2500) + 50)**(1/3)) - (-1/2 - sqrt(3)*I/2)*(sqrt(-x**3/27 + 2500) + 50)**(1/3), 
z == -x/(3*(-1/2 + sqrt(3)*I/2)*(sqrt(-x**3/27 + 2500) + 50)**(1/3)) - (-1/2 + sqrt(3)*I/2)*(sqrt(-x**3/27 + 2500) + 50)**(1/3)]