Lucian Fuchs
Lucian Fuchs

Reputation: 11

Calculate formula in string

Given is a formula(y = mx + b) as a string and a tuple(x, y) with x and y. I s there a python function that uses x and y and calculates the formula ?

As an an example:

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

2 = -4*1 + 6 ➞ True

Upvotes: 0

Views: 202

Answers (2)

David Duran
David Duran

Reputation: 1826

The following function works for any kind of expression (only having x and y variables) without using eval, which may be dangerous:

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)))

Result:

True
False
True

It basically converts the string expression to two mathematical expressions (left-hand and right-hand) using the implicit_multiplication_application transformation, which needs to be used in your case since your are not expliciting the * between a number and a variable. Then, it evaluates both the right and left expression assuming your only symbols are x and y.

Upvotes: 1

tobias_k
tobias_k

Reputation: 82949

If you only want to handle linear equations in the form y = mx + b, you could just use a regular expression to extract m and b (or appropriate default values) and then check the equation:

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)))

Upvotes: 0

Related Questions