pythonsplitequationquadratic

How can I transform any Equation inputted into a standard form in Python?


I am Writing a Simple Quadratic Equation Solver. However I have realized that in order for the code logic to work efficiently I need to convert the input into the standard Quadratic Form no matter what the user provides.

Standard Form of Quadratic Equation : ax**2 + bx + c = 0

Example:
If the user inputs something like 4x(2) + 5x = 6
I need a method to convert it into 4x(2) + 5x - 6 = 0
*here () indicate to the power of

Here's my code for additional Context and Reference

import re
import math

    
def eq_split(eq):
    tokens=re.split(r"[x\*\*2|x|=]", eq)
    while("" in tokens):
        tokens.remove("")
    print(tokens)
    coeff={}
    coeff["a"] = eval(tokens[0]) 
    coeff["b"] = eval(tokens[1])
    coeff["c"] = eval(tokens[2])
    return coeff

def quad(eq):
    coeff=eq_split(eq)
    for key in coeff:
        coeff[key] = int(coeff[key])
    
    delta = coeff["b"]**2 - 4*coeff["a"]*coeff["c"]
    if delta < 0:
        print("There are no real roots.")
        return None
    elif delta == 0:
        sol1 = -coeff["b"] / (2*coeff["a"])
        print(f"The only real root is {sol1}")
        return [sol1]
    else:
        sol1 = (-coeff["b"] + math.sqrt(delta)) / (2*coeff["a"])
        sol2 = (-coeff["b"] - math.sqrt(delta)) / (2*coeff["a"])
        print(f"The two real roots are {sol1} and {sol2}")
        return [sol1,sol2]
        
    

v=quad("4x**2+5x=6")
print(v) 

Open to all Suggestions and methods, but looking for a method without any additional libraries, as this is a learning exercise.

Here's What I've got so for but its not working obviously

    import re
def arrange_eq(eq):
    tokens=re.split("=", eq)

if((tokens[1]=="0")or(tokens[1]=="")):
    return eq
else:
    if("x" not in tokens[1]):
        var=tokens[0]+str(-int(tokens[1]))
        return var
    else:
        tokens[1].strip()
        if(tokens[1][0].isdigit()):
            newexp="+".join(tokens[1])
        elif(tokens[1][0]=="-"):
            newexp="+".join(tokens[1][1:])

        newexp=tokens[1][1:].replace("+", "-").replace("-", "+")

        var=tokens[0]+newexp
        return var

Thank You.


Solution

  • Here's Another Simpler Method....I came up with using lists....thanks to the way C treats its lists....Here's the Code:

    def change_signs(expression):
        if (expression[0].isdigit()):
            expression="+"+expression
        exp=[]
        for i in range(len(expression)):
            exp.append(expression[i])
        for i in range(len(exp)):
            if(exp[i]=="+"):
                exp[i]="-"
            elif(exp[i]=="-"):
                exp[i]="+"
        while " " in exp:
            exp.remove(" ")
        result=""
        for i in exp:
            result += i
        return result
    
    expression = "4-5x-3y"
    result = change_signs(expression)
    print(result)  # Output: +4+5x-3y