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: