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

2024-06-16 10:46:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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中使用solve函数,但它是更大项目的一部分。 该函数顺便解决了联立方程组


Tags: 函数inreforinputvarintenter
1条回答
网友
1楼 · 发布于 2024-06-16 10:46:08

您使用的函数用于求解具有两个变量xy的线性方程组。您需要使用的语法是以下“第一个方程;第二个方程”:

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

如果您运行它,您将得到以下结果:(1.5, 1.0)

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

相关问题 更多 >