用线性表写一个一元函数的加减乘法运算
时间: 2023-10-09 08:08:58 浏览: 48
可以使用顺序表或链表来实现一元函数的加减乘法运算。以下是用顺序表实现的示例代码:
```python
class Polynomial:
def __init__(self, coefficients):
self.coefficients = coefficients
def __add__(self, other):
result = [0] * max(len(self.coefficients), len(other.coefficients))
for i in range(len(self.coefficients)):
result[i] += self.coefficients[i]
for i in range(len(other.coefficients)):
result[i] += other.coefficients[i]
return Polynomial(result)
def __sub__(self, other):
result = [0] * max(len(self.coefficients), len(other.coefficients))
for i in range(len(self.coefficients)):
result[i] += self.coefficients[i]
for i in range(len(other.coefficients)):
result[i] -= other.coefficients[i]
return Polynomial(result)
def __mul__(self, other):
result = [0] * (len(self.coefficients) + len(other.coefficients) - 1)
for i in range(len(self.coefficients)):
for j in range(len(other.coefficients)):
result[i+j] += self.coefficients[i] * other.coefficients[j]
return Polynomial(result)
```
以上代码中,Polynomial类表示一元多项式,coefficients属性存储多项式的系数。__add__()、__sub__()、__mul__()分别实现了多项式的加、减、乘运算。这里使用了顺序表来存储多项式系数,因为顺序表在随机访问、下标操作等方面具有优势。如果使用链表,代码会更复杂一些,但是可以避免顺序表扩容的问题。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.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)