首页 > 解决方案 > 计算字符串中的公式

问题描述

给定一个公式(y = mx + b)作为字符串和一个带有 x 和 y 的元组(x,y)。是否有使用 x 和 y 并计算公式的 python 函数?

举个例子:

def calculate("y = -4x + 6", (1, 2)) ➞ True

2 = -4*1 + 6 ➞ 真

标签: pythonpython-3.xmath

解决方案


以下函数适用于任何类型的表达式(仅具有xy变量)而不使用 using eval,这可能很危险:

from sympy import symbols
from sympy.parsing.sympy_parser import parse_expr, standard_transformations, implicit_multiplication_application

def calculate(str_formula, tuple_xy):
    # Convert left and right expression
    expr_left = parse_expr(str_formula.split("=")[0], transformations=(standard_transformations + (implicit_multiplication_application,)))
    expr_right=parse_expr(str_formula.split("=")[1], transformations=(standard_transformations + (implicit_multiplication_application,)))

    # Symbols used
    x, y = symbols('x y')

    # Evaluate left and right expression
    eval_left = expr_left.subs(x, tuple_xy[0])
    eval_left = eval_left.subs(y, tuple_xy[1])
    eval_right = expr_right.subs(x, tuple_xy[0])
    eval_right = eval_right.subs(y, tuple_xy[1])

    # Comparison
    if eval_left==eval_right:
        return True
    else:
        return False

str_formula = "y=-4x + 6"
print(calculate(str_formula, (1, 2)))
print(calculate(str_formula, (0, 2)))
print(calculate(str_formula, (0, 6)))

结果:

True
False
True

它基本上使用转换将字符串表达式转换为两个数学表达式(左手和右手)implicit_multiplication_application,这需要在您的情况下使用,因为您没有明确*数字和变量之间的关系。x然后,假设您唯一的符号是and ,它会计算左右表达式y


推荐阅读