问题描述
def solve(eq,var=('x','y')):
import re
var_re = re.compile(r'(\+|\-)\s*(\d*)\s*\*?\s*(x|y)')
const_re = re.compile(r'(\+|\-)\s*(\-?\d+)$')
constants,eqns,coeffs,default = [],[],{'x': [],'y': []},{'': '1'}
for e in eq.split(';'):
eq1 = e.replace("="," - ").strip()
if not eq1.startswith('-'):
eq1 = '+' + eq1
eqns.append(eq1)
var_eq1,var_eq2 = map(var_re.findall,eqns)
constants = [-1*int(x[0][1]) for x in map(const_re.findall,eqns)]
[coeffs[x[2]].append(int((x[0]+ default.get(x[1],x[1])).strip())) for x in (var_eq1 + var_eq2)]
ycoeff = coeffs['y']
xcoeff = coeffs['x']
# Adjust equations to take out y and solve for x
if ycoeff[0]*ycoeff[1] > 0:
ycoeff[1] *= -1
xcoeff[0] *= ycoeff[1]
constants[0] *= -1*ycoeff[1]
else:
xcoeff[0] *= -1*ycoeff[1]
constants[0] *= ycoeff[1]
xcoeff[1] *= ycoeff[0]
constants[1] *= -1*ycoeff[0]
# Obtain x
xval = sum(constants)*1.0/sum(xcoeff)
# Now solve for y using value of x
z = eval(eqns[0],{'x': xval,'y': 1j})
yval = -z.real*1.0/z.imag
return (xval,yval)
equation1 = int(input(("Enter the first equation: "))
num1 = int(input("Enter the second equation: "))
print (solve(equation1; num1))
具有和不具有int和
num3 = input("Enter both equations using semicolon between them: ")
solve('num3')
和
b = int(input(("Enter both equations using semicolon between them: "))
print("The prime factors of",b,"are",solve(b))
但有类似错误消息
Traceback (most recent call last):
File "C:/Users/ABDELRAHMANSHERIF/ujn.py",line 45,in <module>
solve('num3')
File "C:/Users/ABDELRAHMANSHERIF/ujn.py",line 15,in solve
var_eq1,eqns)
ValueError: not enough values to unpack (expected 2,got 1)
和其他一些错误消息
那么我该如何将输入函数放在用户输入方程式的位置,并加以解决。我知道我可以在shell中使用solve函数,但这是更大项目的一部分。 该函数顺便求解联立方程。
解决方法
您使用的函数旨在解决带有两个变量x
和y
的线性方程组。您需要使用的语法为以下“ first_equation; second_equation”:
equation1 = "2*x+3*y=6;4*x+9*y=15"
print(solve(equation1))
如果运行它,将得到以下结果:(1.5,1.0)
为了具有良好的编写功能,最好的方法是在函数名称后添加docstring(或doctest),以便知道如何调用它。