帮我写代码实现一元多项式的相加
时间: 2023-05-20 13:02:51 浏览: 48
当然可以,以下是一元多项式相加的代码实现:
```python
class Polynomial:
def __init__(self, coeffs):
self.coeffs = coeffs
def __add__(self, other):
res_coeffs = []
i, j = 0, 0
while i < len(self.coeffs) and j < len(other.coeffs):
if self.coeffs[i][1] == other.coeffs[j][1]:
res_coeffs.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_coeffs.append(self.coeffs[i])
i += 1
else:
res_coeffs.append(other.coeffs[j])
j += 1
while i < len(self.coeffs):
res_coeffs.append(self.coeffs[i])
i += 1
while j < len(other.coeffs):
res_coeffs.append(other.coeffs[j])
j += 1
return Polynomial(res_coeffs)
def __str__(self):
res = ""
for i in range(len(self.coeffs)):
if self.coeffs[i][0] == 0:
continue
if self.coeffs[i][0] > 0 and i > 0:
res += "+"
res += str(self.coeffs[i][0])
if self.coeffs[i][1] > 0:
res += "x"
if self.coeffs[i][1] > 1:
res += "^" + 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)
```
这段代码实现了一元多项式的相加,其中 `Polynomial` 类表示一个多项式,`coeffs` 属性表示多项式的系数,是一个列表,其中每个元素是一个二元组,第一个元素表示系数,第二个元素表示指数。`__add__` 方法实现了多项式的相加,返回一个新的多项式对象。`__str__` 方法用于将多项式转换为字符串,方便输出。
相关推荐
















