如何在不收到错误消息的情况下实现对特定代码的输入功能

How to implement input function to a specific code without getting error messages

这是我定义的函数的全部代码

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, var_eq2 = map(var_re.findall, eqns)
  ValueError: not enough values to unpack (expected 2, got 1)

和其他一些错误消息

那么我怎样才能将输入函数放在用户输入方程式并得到求解的地方。我知道我可以只使用 shell 中的求解函数,但它是更大项目的一部分。 函数顺便求解联立方程

您使用的函数旨在求解具有两个变量 xy 的线性方程组。您需要使用的语法如下 "first_equation;second_equation" :

equation1 = "2*x+3*y=6;4*x+9*y=15"
print(solve(equation1))

如果你 运行 它,你将得到结果:(1.5, 1.0)

为了函数写得好,最好在函数名后面加上docstring(或doctest),以便知道如何调用它。