如何在Python中正确打印线性方程的标准形式?
线性方程标准式打印优化问题
问题背景
实现两点转Ax + By + C = 0形式线性方程的程序,打印时存在以下问题:
- 保留x、y项的系数1(如系数为1时显示
1y,期望为y) - 系数为0时未移除对应项(如系数为0时显示
0x,期望直接去掉该项) - 常数项符号处理错误(如
+ -2期望显示- 2)
示例:输入点(0,2)和(3,2)时,程序输出0x + 1y + -2 = 0,但期望输出y - 2 = 0。
现有代码:
import math def points_to_standard_form(point1, point2): x1, y1 = point1 x2, y2 = point2 A = y1 - y2 B = x2 - x1 C = x1 * y2 - x2 * y1 if A < 0: A, B, C = -A, -B, -C gcd = math.gcd(A, math.gcd(B, C)) A, B, C = A // gcd, B // gcd, C // gcd return A, B, C x1 = int(input("")) y1 = int(input("")) x2 = int(input("")) y2 = int(input("")) point1 = (x1, y1) point2 = (x2, y2) A, B, C = points_to_standard_form(point1, point2) if B >= 0: print(f"{A}x + {B}y + {C} = 0") else: print(f"{A}x - {-B}y + {C} = 0")
优化方案
通过构建项列表的方式,避免大量if语句,分步骤处理每个项的显示逻辑:
- 编写辅助函数处理单个变量项,覆盖系数为0、1、-1的特殊情况
- 收集所有非零的变量项,拼接时自动处理符号
- 单独处理常数项的符号,与变量项整合为完整表达式
改进后的代码:
import math def points_to_standard_form(point1, point2): x1, y1 = point1 x2, y2 = point2 A = y1 - y2 B = x2 - x1 C = x1 * y2 - x2 * y1 if A < 0: A, B, C = -A, -B, -C # 处理两点重合的极端情况 if A == 0 and B == 0: return 0, 0, 0 gcd = math.gcd(abs(A), math.gcd(abs(B), abs(C))) A, B, C = A // gcd, B // gcd, C // gcd return A, B, C def format_term(coeff, var): """格式化单个变量项,处理系数为0、1、-1的特殊情况""" if coeff == 0: return "" elif coeff == 1: return var elif coeff == -1: return f"-{var}" return f"{coeff}{var}" x1 = int(input("")) y1 = int(input("")) x2 = int(input("")) y2 = int(input("")) point1 = (x1, y1) point2 = (x2, y2) A, B, C = points_to_standard_form(point1, point2) # 收集非零变量项 terms = [] x_term = format_term(A, 'x') if x_term: terms.append(x_term) y_term = format_term(B, 'y') if y_term: terms.append(y_term) # 构建方程主体 equation = "" if terms: equation = terms[0] # 处理后续变量项的符号 for term in terms[1:]: if term.startswith('-'): equation += f" {term}" else: equation += f" + {term}" # 处理常数项 if C != 0: if C > 0: equation += f" + {C}" else: equation += f" - {-C}" else: # 极端情况:两点重合 equation = f"{C} = 0" # 拼接等式右侧 equation += " = 0" print(equation)
测试验证
- 输入
0、2、3、2,输出y - 2 = 0,符合预期 - 输入
1、1、2、3,输出2x - y - 1 = 0 - 输入
0、0、1、1,输出x - y = 0
内容的提问来源于stack exchange,提问作者HarmanT13
相关产品推荐
相关产品推荐

