Python新手如何实现符合指定要求的Polynominal多项式类?
Polynominal类实现方案
核心问题修复
你当前代码打印对象地址的根本原因是:Python类的实例方法第一个参数永远是实例本身,你没有显式声明self,导致*args的第一个元素就是实例对象,遍历拼接时就会出现内存地址输出。
完整实现代码
class Polynominal: def __init__(self, *args): # 校验所有系数都是整数 for coeff in args: if not isinstance(coeff, int): raise TypeError("所有系数必须为整数") # 存储系数,自动去掉末尾的无效0 self.coeffs = list(args) while len(self.coeffs) > 0 and self.coeffs[-1] == 0: self.coeffs.pop() # 空多项式处理 if not self.coeffs: self.coeffs = [0] @classmethod def from_iterable(cls, iterable): # 从可迭代对象创建实例 return cls(*iterable) def get_degree(self): # 返回多项式次数 return len(self.coeffs) - 1 def __str__(self): terms = [] for power, coeff in enumerate(self.coeffs): if coeff == 0: continue # 处理系数绝对值 abs_coeff = abs(coeff) # 处理项的主体部分 if power == 0: term = str(abs_coeff) elif power == 1: term = f"{abs_coeff}x" if abs_coeff != 1 else "x" else: term = f"{abs_coeff}x^{power}" if abs_coeff != 1 else f"x^{power}" terms.append((coeff > 0, term)) # 空多项式返回空字符串 if not terms: return "" # 拼接符号 res = [] for idx, (is_positive, term) in enumerate(terms): if idx == 0: res.append(term if is_positive else f"-{term}") else: res.append(f" + {term}" if is_positive else f" - {term}") return "".join(res) def __call__(self, x): # 霍纳法则实现多项式求值 result = 0 for coeff in reversed(self.coeffs): result = result * x + coeff return result def __eq__(self, other): # 相等判断 if not isinstance(other, Polynominal): return False return self.coeffs == other.coeffs def __add__(self, other): # 多项式相加 if not isinstance(other, Polynominal): raise TypeError("只能与Polynominal实例相加") max_len = max(len(self.coeffs), len(other.coeffs)) # 补0对齐长度 self_padded = self.coeffs + [0] * (max_len - len(self.coeffs)) other_padded = other.coeffs + [0] * (max_len - len(other.coeffs)) new_coeffs = [a + b for a, b in zip(self_padded, other_padded)] return Polynominal(*new_coeffs) def __mul__(self, other): # 多项式相乘 if not isinstance(other, Polynominal): raise TypeError("只能与Polynominal实例相乘") new_len = len(self.coeffs) + len(other.coeffs) - 1 new_coeffs = [0] * new_len for i, a in enumerate(self.coeffs): for j, b in enumerate(other.coeffs): new_coeffs[i + j] += a * b return Polynominal(*new_coeffs)
功能验证示例
# 字符串转换测试 print(str(Polynominal())) # 输出空字符串 print(str(Polynominal(1, 2, 3))) # 输出 1 + 2x + 3x^2 print(str(Polynominal(1, -1, 1, -1))) # 输出 1 - x + x^2 - x^3 print(str(Polynominal(0, 2, 0))) # 输出 2x # 求值测试 p = Polynominal(1, 2) print(p(1)) # 3 print(p(2)) # 5 # 次数测试 print(Polynominal().get_degree()) # 0 print(Polynominal(1, 2, 3).get_degree()) # 2 # 相等测试 print(Polynominal() == Polynominal(0)) # True print(Polynominal(1, 2, 3) == Polynominal(1, 2, 3)) # True # 相加测试 print(Polynominal(1,1,1) + Polynominal(2,2,2) == Polynominal(3,3,3)) # True # 相乘测试 print(Polynominal(1,1) * Polynominal(2,2) == Polynominal(2,4,2)) # True # from_iterable测试 print(Polynominal.from_iterable([1,2,3]) == Polynominal(1,2,3)) # True
内容的提问来源于stack exchange,提问作者xyzxyzxyz
相关产品推荐
相关产品推荐

