有没有一种简单的方法来制作一个函数来反转算法,例如:
>>> value = inverse("y = 2*x+3")
>>> print(value)
"x = (y-3)/2"
如果您不能为该函数编写实际代码,请向我推荐可以简化此任务的工具。该函数将仅用于反转带有 +、-、* 和/
的算法最佳答案
您应该尝试使用 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'
关于python - 在 Python 中反转代数表达式字符串的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16948965/