Python中的二次方程

huangapple go评论102阅读模式
英文:

Quadratic equation in Python

问题

这是我的代码。有人可以帮忙解决问题吗?在下面的代码中,我做了一切,但它不起作用。

  1. def read_equation(textfile: str) -> str:
  2. with open(textfile, 'r') as file:
  3. equation = file.read()
  4. return equation
  1. def get_coefficients(input_str: str, coef: str) -> int:
  2. for i in input_str.split():
  3. if i.endswith(coef):
  4. try:
  5. value = i.replace(coef, "", 1)
  6. if not value or value == "+":
  7. value = "1"
  8. elif value == "-":
  9. value = "-1"
  10. return int(value)
  11. except ValueError as err:
  12. print(err)
  13. raise TypeError(f"其他符号 {coef},不是整数。")

查找系数

  1. def get_a_b_c(input_str: str) -> tuple:
  2. a = get_coefficients(input_str, "x^2")
  3. b = get_coefficients(input_str, "x")
  4. c = get_coefficients(input_str, "")
  5. return a, b, c

查找判别式

  1. def solve_quadratic_equation(a: int, b: int, c: int) -> str:
  2. d = b ** 2 - 4 * a * c
  3. if d > 0:
  4. x1 = (-b + d ** 0.5) / (2 * a)
  5. x2 = (-b - d ** 0.5) / (2 * a) # 找到根
  6. roots = f"x1 = {x1}\nx2 = {x2}"
  7. elif d == 0:
  8. x = -b / (2 * a)
  9. roots = f"x = {x}"
  10. else:
  11. roots = "无根"
  12. return roots

根写入文件

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

主函数

  1. def main():
  2. user_input = read_equation(textfile="equation.txt")
  3. coefficients = get_a_b_c(user_input)
  4. roots = solve_quadratic_equation(*coefficients)
  5. write_roots(output=roots, textfile="equation.txt")
  6. if __name__ == "__main__":
  7. main()

我尝试获取根并将其写入现有文件,但它不起作用。

英文:

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

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

Finding coefficients

  1. def get_a_b_c(input_str: str) -> tuple:
  2. a = get_coefficients(input_str, "x^2")
  3. b = get_coefficients(input_str, "x")
  4. c = get_coefficients(input_str, "")
  5. return a, b, c

finding discriminant

  1. def solve_quadratic_equation(a: int, b: int, c: int) -> str:
  2. d = b ** 2 - 4 * a * c
  3. if d > 0:
  4. x1 = (-b + d ** 0.5) / (2 * a)
  5. x2 = (-b - d ** 0.5) / (2 * a) # finding roots
  6. roots = f"x1 = {x1}\nx2 = {x2}"
  7. elif d == 0:
  8. x = -b / (2 * a)
  9. roots = f"x = {x}"
  10. else:
  11. roots = "No roots"
  12. return roots

roots in file

  1. def write_roots(output: str, textfile: str) -> None:
  2. with open(textfile, 'a') as file:
  3. file.write('\n')
  4. file.write(output)
  5. main function:
  6. def main():
  7. user_input = read_equation(textfile="equation.txt")
  8. coefficients = get_a_b_c(user_input)
  9. roots = solve_quadratic_equation(*coefficients)
  10. write_roots(output=roots, textfile="equation.txt")
  1. if __name__ == "__main__":
  2. main()

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

答案1

得分: 0

Here is the translated content:

事实上,你有问题的地方是:

  1. c = get_coefficients(input_str, "")

这一行没有正确地获取常数的系数。

现在,如果你运行你的当前代码:

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

你会得到:

  1. ----> 5 c = get_coefficients(input_str, "")
  2. 6 return a, b, c
  3. C:\Users\NAVIGA~1\AppData\Local\Temp/ipykernel_27960/1668498165.py 中的 get_coefficients(input_str, coef)
  4. 11 except ValueError as err:
  5. 12 print(err)
  6. ---> 13 raise TypeError(f"Other symbol {coef}, not an int.")
  7. TypeError: Other symbol , not an int.

解决方法:

你可以通过在方程周围使用 split(' =') 来获取 c 的系数。

  1. def get_a_b_c(input_str: str) -> tuple:
  2. a = get_coefficients(input_str, "x^2")
  3. b = get_coefficients(input_str, "x")
  4. c = int(input_str.split(' =')[0][-1]) # 从拆分中获取 c
  5. return a, b, c

  1. print(get_a_b_c("1x^2 - 10x + 2 = 0"))
  2. #输出
  3. (1, 10, 2)

现在,你可以使用你所有的公式:

  1. def solve_quadratic_equation(a: int, b: int, c: int) -> str:
  2. d = b ** 2 - 4 * a * c
  3. if d > 0:
  4. x1 = (-b + d ** 0.5) / (2 * a)
  5. x2 = (-b - d ** 0.5) / (2 * a) # 寻找根
  6. roots = f"x1 = {x1}\nx2 = {x2}"
  7. elif d == 0:
  8. x = -b / (2 * a)
  9. roots = f"x = {x}"
  10. else:
  11. roots = "没有根"
  12. return roots
  13. coefficients = get_a_b_c("1x^2 - 10x + 2 = 0")
  14. roots = solve_quadratic_equation(*coefficients)
  15. print(roots)
  16. #输出
  17. 'x1 = -0.2041684766872809\nx2 = -9.79583152331272'
英文:

Actually, you have problem with :

  1. 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:

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

you will get:

  1. ----> 5 c = get_coefficients(input_str, "")
  2. 6 return a, b, c
  3. C:\Users\NAVIGA~1\AppData\Local\Temp/ipykernel_27960/1668498165.py in get_coefficients(input_str, coef)
  4. 11 except ValueError as err:
  5. 12 print(err)
  6. ---> 13 raise TypeError(f"Other symbol {coef}, not an int.")
  7. TypeError: Other symbol , not an int.

Workaround:

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

  1. def get_a_b_c(input_str: str) -> tuple:
  2. a = get_coefficients(input_str, "x^2")
  3. b = get_coefficients(input_str, "x")
  4. c = int(input_str.split(' =')[0][-1]) # getting c from split
  5. return a, b, c

  1. print(get_a_b_c("1x^2 - 10x + 2 = 0"))
  2. #output
  3. (1, 10, 2)

Now, you can use all your formulas:

  1. def solve_quadratic_equation(a: int, b: int, c: int) -> str:
  2. d = b ** 2 - 4 * a * c
  3. if d > 0:
  4. x1 = (-b + d ** 0.5) / (2 * a)
  5. x2 = (-b - d ** 0.5) / (2 * a) # finding roots
  6. roots = f"x1 = {x1}\nx2 = {x2}"
  7. elif d == 0:
  8. x = -b / (2 * a)
  9. roots = f"x = {x}"
  10. else:
  11. roots = "No roots"
  12. return roots
  13. coefficients = get_a_b_c("1x^2 - 10x + 2 = 0")
  14. roots = solve_quadratic_equation(*coefficients)
  15. print(roots)
  16. #output
  17. 'x1 = -0.2041684766872809\nx2 = -9.79583152331272'

huangapple
  • 本文由 发表于 2023年6月26日 20:51:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556872.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定