多项式加法python代码
时间: 2024-06-20 08:03:10 浏览: 9
多项式加法的 Python 代码如下所示:
```
class Poly:
def __init__(self, coefs):
self.coefs = coefs
def __add__(self, other):
if isinstance(other, Poly):
new_coefs = []
for i in range(max(len(self.coefs), len(other.coefs))):
c1 = self.coefs[i] if i < len(self.coefs) else 0
c2 = other.coefs[i] if i < len(other.coefs) else 0
new_coefs.append(c1 + c2)
return Poly(new_coefs)
else:
raise TypeError('Poly objects can only be added to Poly objects')
def __str__(self):
terms = []
for i, c in enumerate(self.coefs):
if c != 0:
if i == 0:
term = str(c)
elif i == 1:
term = f'{c}x'
else:
term = f'{c}x^{i}'
terms.append(term)
return ' + '.join(reversed(terms)) or '0'
p1 = Poly([1, 2, 3])
p2 = Poly([2, -1, 1])
print(f'p1: {p1}')
print(f'p2: {p2}')
print(f'p1 + p2: {p1 + p2}')
```
该代码定义了一个名为 Poly 的类,用于表示多项式。其中,`__init__` 方法用于初始化多项式的系数,`__add__` 方法用于计算两个多项式之和,`__str__` 方法用于返回多项式的字符串表示。
通过以上代码,我们可以得到两个多项式 `p1` 和 `p2`,它们的系数分别为 `[1, 2, 3]` 和 `[2, -1, 1]`。然后,我们可以通过 `p1 + p2` 计算它们的和。最后,使用 `print` 输出多项式的字符串表示。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)