一元多项式加减乘法计算代码
时间: 2023-12-20 09:53:42 浏览: 69
好的,以下是一元多项式加减乘法计算代码示例:
```python
class Polynomial:
def __init__(self, coeffs):
self.coeffs = coeffs
def __add__(self, other):
res = []
len1, len2 = len(self.coeffs), len(other.coeffs)
for i in range(max(len1, len2)):
x = self.coeffs[i] if i < len1 else 0
y = other.coeffs[i] if i < len2 else 0
res.append(x + y)
return Polynomial(res)
def __sub__(self, other):
res = []
len1, len2 = len(self.coeffs), len(other.coeffs)
for i in range(max(len1, len2)):
x = self.coeffs[i] if i < len1 else 0
y = other.coeffs[i] if i < len2 else 0
res.append(x - y)
return Polynomial(res)
def __mul__(self, other):
res = [0] * (len(self.coeffs) + len(other.coeffs))
for i, x in enumerate(self.coeffs):
for j, y in enumerate(other.coeffs):
res[i + j] += x * y
return Polynomial(res)
def __str__(self):
return " + ".join((f"{self.coeffs[i]}x^{i}" for i in range(len(self.coeffs)) if self.coeffs[i]))
p1 = Polynomial([1, 2, 3]) # 1x^2 + 2x^1 + 3x^0
p2 = Polynomial([4, 5, 6]) # 4x^2 + 5x^1 + 6x^0
print(f"p1 + p2 = {p1 + p2}")
print(f"p1 - p2 = {p1 - p2}")
print(f"p1 * p2 = {p1 * p2}")
```
希望以上代码能够帮到您!现在,请问您有什么其它问题吗?
阅读全文