Quadratic equation in Python

128 Views Asked by At

here is my code. Can anybody help to solve the problem? In the code below everything what I made but it doesn't work.

    def read_equation(textfile: str) -> str:
        with open(textfile, 'r') as file:
            equation = file.read()
        return equation
    def get_coefficients(input_str: str, coef: str) -> int:
        for i in input_str.split():
            if i.endswith(coef):
                try:
                    value = i.replace(coef, "", 1)
                    if not value or value == "+":
                        value = "1"
                    elif value == "-":
                        value == "-1"
                    return int(value)
                except ValueError as err:
                    print(err)
                    raise TypeError(f"Other symbol {coef}, not an int.")

Finding coefficients

    def get_a_b_c(input_str: str) -> tuple:

        a = get_coefficients(input_str, "x^2")
        b = get_coefficients(input_str, "x")
        c = get_coefficients(input_str, "")
        return a, b, c

finding discriminant

    def solve_quadratic_equation(a: int, b: int, c: int) -> str:
        d = b ** 2 - 4 * a * c
        if d > 0:
            x1 = (-b + d ** 0.5) / (2 * a)
            x2 = (-b - d ** 0.5) / (2 * a) # finding roots
            roots = f"x1 = {x1}\nx2 = {x2}"
        elif d == 0:
            x = -b / (2 * a)
            roots = f"x = {x}"
        else:
            roots = "No roots"
        return roots

roots in file

    def write_roots(output: str, textfile: str) -> None:
        with open(textfile, 'a') as file:
            file.write('\n')
            file.write(output)

main function:

    def main():
        user_input = read_equation(textfile="equation.txt")
        coefficients = get_a_b_c(user_input)
        roots = solve_quadratic_equation(*coefficients)
        write_roots(output=roots, textfile="equation.txt")

    if __name__ == "__main__":
        main()

I tried to get roots and write it in existing file, but it doesn't work

1

There are 1 best solutions below

0
Talha Tayyab On BEST ANSWER

Actually, you have problem with :

c = get_coefficients(input_str, "")

this line is not correctly fetching the coefficients for the constant.

Now, if you run your current code with this:

get_coefficients("1x^2 - 10x + 2 = 0")

you will get:

----> 5     c = get_coefficients(input_str, "")
      6     return a, b, c

C:\Users\NAVIGA~1\AppData\Local\Temp/ipykernel_27960/1668498165.py in get_coefficients(input_str, coef)
     11                 except ValueError as err:
     12                     print(err)
---> 13                     raise TypeError(f"Other symbol {coef}, not an int.")

TypeError: Other symbol , not an int.

Workaround:

You can get coefficient of c by using split(' =') around the equation.

def get_a_b_c(input_str: str) -> tuple:

        a = get_coefficients(input_str, "x^2")
        b = get_coefficients(input_str, "x")
        c = int(input_str.split(' =')[0][-1])  # getting c from split
        return a, b, c 

print(get_a_b_c("1x^2 - 10x + 2 = 0"))

#output
(1, 10, 2)

Now, you can use all your formulas:

def solve_quadratic_equation(a: int, b: int, c: int) -> str:
    d = b ** 2 - 4 * a * c
    if d > 0:
        x1 = (-b + d ** 0.5) / (2 * a)
        x2 = (-b - d ** 0.5) / (2 * a) # finding roots
        roots = f"x1 = {x1}\nx2 = {x2}"
    elif d == 0:
        x = -b / (2 * a)
        roots = f"x = {x}"
    else:
        roots = "No roots"
    return roots

coefficients = get_a_b_c("1x^2 - 10x + 2 = 0")

roots = solve_quadratic_equation(*coefficients)

print(roots)

#output

'x1 = -0.2041684766872809\nx2 = -9.79583152331272'