From 278684310df8da3af1a32f5c5d9e540911ac78a7 Mon Sep 17 00:00:00 2001 From: lucas8485 <1443937075@qq.com> Date: Sun, 11 Dec 2022 16:00:02 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E4=BA=86=E7=9F=A9=E9=98=B5?= =?UTF-8?q?=E8=BF=90=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- equation_solver.py | 19 +++++-------------- main.py | 2 +- 2 files changed, 6 insertions(+), 15 deletions(-) diff --git a/equation_solver.py b/equation_solver.py index d990e5e..99528c6 100644 --- a/equation_solver.py +++ b/equation_solver.py @@ -57,18 +57,10 @@ def solve_equation(eq): matrix = np.mat(matrix, int) # 求解线性方程组 try: - result = np.linalg.solve(matrix, constant).tolist() - except np.linalg.LinAlgError: - # 将常数项取负,插入到矩阵的最后一列 - constant = [-x for x in constant] - matrix = np.insert(matrix, matrix.shape[1], constant, axis=1) - # 再次尝试求解 - try: - constant = np.zeros(matrix.shape[0], int) - result = sp.linalg.solve(matrix, constant).tolist() - except Exception as e: - print('无法配平' + str(e)) - return None + result = sp.optimize.lsq_linear(matrix, constant, bounds=(0, None)).x.tolist() + except ValueError: + print('无法配平') + return None # 将结果写入化学方程式,最后一个生成物的系数需要计算得到 last_substance = eq['right'][-1] @@ -76,7 +68,6 @@ def solve_equation(eq): # 计算除最后一种生成物外的所有生成物包含last_atom的系数之和 sum_ = 0 index = 0 - print(result) for each in eq['left']: for atom in each['atoms']: if last_atom in atom: @@ -118,4 +109,4 @@ def expand_to_int(*args): result = [] for each in fractions: result.append(each.numerator * lcm // each.denominator) - return result \ No newline at end of file + return result diff --git a/main.py b/main.py index 0ce3fae..b92af5a 100644 --- a/main.py +++ b/main.py @@ -9,7 +9,7 @@ import equation_solver # 按间距中的绿色按钮以运行脚本。 if __name__ == '__main__': while True: - eq = input('请输入化学方程式:') + eq = input('请输入化学方程式:(输入exit退出)') if eq == 'exit': break try: