python中的方程操作

时间:2016-10-10 02:33:39

标签: python math equation polynomials

您好我想在python中进行方程式操作: 例如,我有:

"3x^2 + 5xy - 5 = 5x^2 + 2xy"

输入等式可以是任何东西。

我需要结果:

"-2x^2 + 3xy - 5 = 0"

我能够提取方程的左手侧和右手侧并将它们分开。请参阅以下代码:

base_equation = raw_input()
no_spaces_equation = base_equation.replace(" ", "")
print no_spaces
left_hand_side = no_spaces[0:no_spaces.index('=')]
print left_hand_side
right_hand_side = no_spaces[no_spaces.index('=')+1:len(no_spaces)]
print right_hand_side

但是我不知道如何检查变量及其符号并添加它们。期待您的帮助。

谢谢!

1 个答案:

答案 0 :(得分:2)

如果你使用字符串,它应该相对简单。

考虑你的例子(我已经使用引号来确保它是一个字符串):

"3x^2 + 5xy - 5 = 5x^2 + 2xy"

显然,您希望将其拆分为不同的部分,然后计算它们。在这种情况下,x ^ 2,xy和数字。您可以通过分析字符串来完成此操作。

为了简化任务,您可能会限制语法,每个术语之间需要一个空格。

以下是使用一些简单的输出格式对术语进行分组的一种示例:

eqn = "3x^2 + 5xy - 5 = 5x^2 + 2xy"
split = eqn.split(" ")

terms = {}
LHS = True # We start by counting terms on the left hand side of the equation
for i in split:
    skip = False
    term = i

    if i is "=":  # Check if we've moved to the right hand side
         LHS = False

    # If the 'term' is actually a symbol and not a term
    if not term.isalnum() and term.count("^") == 0:
        continue

    stripped_digits = 0 # Keep track of the length of the coefficient

    # Remove the coefficient numbers until we get to the term we're interested in
    while term[0].isdigit() or term[0] == "-":
        term = term.lstrip(term[0])
        stripped_digits += 1
        if len(term) == 0:
            term = ""
            break
        # If the 'term' is actually a symbol and not a term
        if not term.isalnum() and term.count("^") == 0 and term != "":
            skip = True            
            break

    if skip: 
        continue

    # Find the coefficient of the term
    coeff = int(i[0:stripped_digits])

    if split[split.index(i) - 1] == "-":
        coeff = -coeff
    if term in terms.keys(): # Check if we've already started counting the term
        if LHS:
            terms[term] += coeff
        else:
            terms[term] -= coeff
    else:
        if LHS:
            terms[term] = coeff
        else:
            terms[term] = -coeff

print(terms)
# Now just format the terms as you choose
output = ""
for key in terms.keys():
    output += str(terms[key]) + key + " + "
output = output.rstrip("+ ")
output += " = 0"
print(output)

这输出以下内容:

{'': -5, 'x^2': -2, 'xy': 3}
-5 + -2x^2 + 3xy = 0

显然,这不是最优雅的解决方案,我相信你会找到更有效的方法来完成大部分工作。但这只是一个如何考虑术语分组的简单例子。