如何在Python多项式代码中去除系数1的显示?
解决方案
你需要在生成多项式字符串时,针对系数为1或-1且指数不为0的情况做特殊处理,以下是修改后的代码:
class Polynomial: # Constructor def __init__(self, polyDict): self.polyDict = polyDict # String Method def __str__(self): polyStr = "" firstTerm = True # 按指数降序排序 for exp, coeff in sorted(self.polyDict.items(), reverse=True): if coeff == 0: continue # 处理系数部分 if firstTerm: if coeff == 1 and exp != 0: # 系数为1且非常数项,不输出1 pass elif coeff == -1 and exp != 0: # 系数为-1且非常数项,只输出负号 polyStr += "-" else: # 其他情况正常输出系数 polyStr += str(coeff) firstTerm = False else: if coeff > 0: polyStr += "+" if coeff != 1 or exp == 0: # 系数不是1,或者是常数项,输出系数 polyStr += str(coeff) else: if coeff == -1 and exp != 0: # 系数为-1且非常数项,只输出负号 polyStr += "-" else: # 其他负系数正常输出 polyStr += str(coeff) # 处理变量部分 if exp > 1: polyStr += f"x^{exp}" elif exp == 1: polyStr += "x" return polyStr print(Polynomial({6:-3, 5:6, 4:-1, 3:-2, 2:0, 1:1, 0:-3}))
关键修改说明
- 系数为1的处理:当系数是1且不是常数项(指数≠0)时,不输出数字1,直接拼接变量部分;如果是常数项(指数=0),则正常输出1。
- 系数为-1的处理:当系数是-1且不是常数项时,只输出负号
-,不输出数字1;常数项则正常输出-1。 - 符号拼接优化:非第一项的正系数先加
+,再判断是否需要输出数字,避免出现+1x这类格式。
运行修改后的代码,输出结果为:-3x^6+6x^5-x^4-2x^3+x-3,符合隐藏系数1的规则。
内容的提问来源于stack exchange,提问作者Cannon Ahrens
相关产品推荐
相关产品推荐

