我正在编写一个简单的二次方程求解器。但是我已经意识到,为了使代码逻辑有效地工作,无论用户提供什么,我都需要将输入转换为标准的二次形式。
二次方程的标准形式:ax**2 + bx + c = 0
例子:
如果用户输入类似 4x(2) + 5x = 6
我需要一种方法将其转换为 4x(2) + 5x - 6 = 0
*这里()表示
这是我的额外上下文和参考代码
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)
接受所有建议和方法,但寻找一种没有任何额外库的方法,因为这是一个学习练习。
这就是我得到的,但它显然不起作用
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:
if(tokens[1][0].isdigit()):
newexp="+".join(tokens[1])
elif(tokens[1][0]=="-"):
newexp="+".join(tokens[1][1:])
newexp[1][1:].replace("+", "-").replace("-", "+")
var=tokens[0]+tokens[1]
return var
谢谢。