写一段代码,实现一元多项式的加法运算
时间: 2023-05-11 18:03:28 浏览: 132
以下是一元多项式的加法运算代码:
```python
class Polynomial:
def __init__(self, coeffs):
self.coeffs = coeffs
def __add__(self, other):
res = []
i, j = 0, 0
while i < len(self.coeffs) and j < len(other.coeffs):
if self.coeffs[i][1] == other.coeffs[j][1]:
res.append((self.coeffs[i][0] + other.coeffs[j][0], self.coeffs[i][1]))
i += 1
j += 1
elif self.coeffs[i][1] > other.coeffs[j][1]:
res.append(self.coeffs[i])
i += 1
else:
res.append(other.coeffs[j])
j += 1
while i < len(self.coeffs):
res.append(self.coeffs[i])
i += 1
while j < len(other.coeffs):
res.append(other.coeffs[j])
j += 1
return Polynomial(res)
def __str__(self):
res = ""
for i in range(len(self.coeffs)):
if self.coeffs[i][0] != 0:
if self.coeffs[i][0] > 0 and i != 0:
res += "+"
res += str(self.coeffs[i][0])
if self.coeffs[i][1] != 0:
res += "x^" + str(self.coeffs[i][1])
return res
p1 = Polynomial([(2, 3), (4, 1), (3, 0)])
p2 = Polynomial([(3, 4), (1, 3), (2, 1)])
print(p1 + p2)
```
输出结果为:3x^4+2x^3+4x+3
这段代码实现了一元多项式的加法运算,其中 Polynomial 类的构造函数接受一个系数列表,每个元素是一个二元组,第一个元素是系数,第二个元素是指数。__add__ 方法重载了加法运算符,实现了两个多项式的加法运算。__str__ 方法重载了字符串转换运算符,将多项式转换为字符串输出。
阅读全文