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
Actually, you have problem with :
this line is not correctly fetching the coefficients for the constant.
Now, if you run your current code with this:
you will get:
Workaround:
You can get coefficient of c by using
split(' =')around the equation.Now, you can use all your formulas: