多项式编写类
时间: 2023-08-08 19:09:38 浏览: 89
多项式的设计与实现,多项式的加减乘除
好的,我可以为您编写一个多项式类。以下是一个基本的多项式类实现,您可以在此基础上进行扩展:
```python
class Polynomial:
def __init__(self, coeffs):
self.coeffs = coeffs
def __repr__(self):
return "Polynomial({})".format(self.coeffs)
def __str__(self):
terms = []
for i, coeff in enumerate(self.coeffs):
if coeff == 0:
continue
elif i == 0:
terms.append(str(coeff))
elif i == 1:
terms.append("{}x".format(coeff))
else:
terms.append("{}x^{}".format(coeff, i))
return " + ".join(reversed(terms))
def __add__(self, other):
if isinstance(other, Polynomial):
return Polynomial([a + b for a, b in zip(self.coeffs, other.coeffs)])
else:
return Polynomial([a + other for a in self.coeffs])
def __sub__(self, other):
if isinstance(other, Polynomial):
return Polynomial([a - b for a, b in zip(self.coeffs, other.coeffs)])
else:
return Polynomial([a - other for a in self.coeffs])
def __mul__(self, other):
if isinstance(other, Polynomial):
result = [0] * (len(self.coeffs) + len(other.coeffs) - 1)
for i, a in enumerate(self.coeffs):
for j, b in enumerate(other.coeffs):
result[i+j] += a * b
return Polynomial(result)
else:
return Polynomial([a * other for a in self.coeffs])
```
这个类有一个参数coeffs,这是一个列表,包含多项式的系数,例如:
```python
p1 = Polynomial([1, 2, 3]) # 表示多项式 1 + 2x + 3x^2
p2 = Polynomial([2, 4, 1]) # 表示多项式 2 + 4x + x^2
```
这个类实现了多项式的加、减、乘法运算,以及__repr__()和__str__()方法,它们分别用于返回多项式的字符串表示形式和Python表达式形式。您可以通过调用这些方法来打印多项式的值。
希望这个多项式类符合您的需求,如果您有任何其他问题,请随时问我。
阅读全文