0

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.

  • For such a problem, you do not need to get the equation. All you need is `a`, `b`, and `c`. as `ax**2+bx+c=0`. If you want to solve the problem, what you need is a parser and it's not an easy task to do. Imagine one can write the equation as `bx+c=-ax**2`... – MSH Apr 08 '23 at 12:38
  • Thanks...Yes i do need just a, b and c but if someone enters -c after the = sign it will be treated the same as before the = sign, thus the need for a system. – Rishit Chakraborty Apr 08 '23 at 12:48

2 Answers2

0

Found The Answer.....It's Regex....bit complicated and still don't completely understand how it works....but first rule of programming folks....Here's what I came Up with....

def change_signs(expression):
    if expression[0].isdigit():
        expression = "+" + expression

    operands = re.split("([+-])", expression)
    for i in range(1, len(operands), 2):
        if operands[i] == "+":
            operands[i] = "-"
        else:
            operands[i] = "+"
            
    expression = "".join(operands)

    return expression 


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

    if((tokens[1]=="0")or(tokens[1]=="")):
        return eq
    else:
        rev=change_signs(tokens[1])
        new_exp=tokens[0]+ rev + "= 0"
        new_exp.strip()
        return  new_exp
0

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