Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用字符串计算公式_Python_Python 3.x_Math - Fatal编程技术网

Python 用字符串计算公式

Python 用字符串计算公式,python,python-3.x,math,Python,Python 3.x,Math,给出了一个公式(y=mx+b),它是一个字符串和一个带有x和y的元组(x,y)。 有一个python函数使用x和y来计算公式吗 例如: def calculate("y = -4x + 6", (1, 2)) ➞ True 2=-4*1+6➞ True以下函数适用于任何类型的表达式(仅具有x和y变量),而不使用eval,这可能是危险的: from sympy import symbols from sympy.parsing.sympy_parser import pars

给出了一个公式(y=mx+b),它是一个字符串和一个带有x和y的元组(x,y)。 有一个python函数使用x和y来计算公式吗

例如:

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

2=-4*1+6➞ True

以下函数适用于任何类型的表达式(仅具有
x
y
变量),而不使用
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

它基本上使用
隐式乘法应用程序
转换将字符串表达式转换为两个数学表达式(左手和右手),这需要在您的案例中使用,因为您没有明确说明数字和变量之间的
*
。然后,它计算右表达式和左表达式,假设您唯一的符号是
x
y

如果您只想处理形式为
y=mx+b
的线性方程,您可以使用正则表达式提取
m
b
(或适当的默认值)然后检查等式:

import re

def calculate(f, xy):
    match = re.match(r"^y = (-?\d*)x( [+-] \d+)?$", f)
    if match:
        m, b = match.groups()
        m = -1 if m == "-" else int(m or 1)
        b = int(b.replace(" ", "")) if b else 0
        x, y = xy
        return y == m * x + b

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

e、 g.使用?是否严格,或者您可以直接规定?然后(取决于安全性限制),您可以使用
eval
如果公式的格式始终为
y=mx+b
,那么用正则表达式提取
m
和b`应该不会太难,然后只需在没有任何奇特库的情况下进行检查即可。我忘记处理m=0的情况,即
y=b
;我将把它作为练习留给感兴趣的读者。。。