对简单的一元多项式相加、相减运算
时间: 2023-08-15 09:06:24 浏览: 157
一元多项式相加相减相乘
4星 · 用户满意度95%
一元多项式相加、相减运算可以使用上面的链表实现。假设有两个多项式 $p_1$ 和 $p_2$,它们的单项式按照指数从大到小排列,可以按照以下方式实现相加、相减运算:
```python
def add(p1, p2):
result = Polynomial()
current_p1 = p1.head.next
current_p2 = p2.head.next
while current_p1 is not None and current_p2 is not None:
if current_p1.exp == current_p2.exp:
result.insert(current_p1.coef + current_p2.coef, current_p1.exp)
current_p1 = current_p1.next
current_p2 = current_p2.next
elif current_p1.exp > current_p2.exp:
result.insert(current_p1.coef, current_p1.exp)
current_p1 = current_p1.next
else:
result.insert(current_p2.coef, current_p2.exp)
current_p2 = current_p2.next
while current_p1 is not None:
result.insert(current_p1.coef, current_p1.exp)
current_p1 = current_p1.next
while current_p2 is not None:
result.insert(current_p2.coef, current_p2.exp)
current_p2 = current_p2.next
return result
def sub(p1, p2):
result = Polynomial()
current_p1 = p1.head.next
current_p2 = p2.head.next
while current_p1 is not None and current_p2 is not None:
if current_p1.exp == current_p2.exp:
result.insert(current_p1.coef - current_p2.coef, current_p1.exp)
current_p1 = current_p1.next
current_p2 = current_p2.next
elif current_p1.exp > current_p2.exp:
result.insert(current_p1.coef, current_p1.exp)
current_p1 = current_p1.next
else:
result.insert(-current_p2.coef, current_p2.exp)
current_p2 = current_p2.next
while current_p1 is not None:
result.insert(current_p1.coef, current_p1.exp)
current_p1 = current_p1.next
while current_p2 is not None:
result.insert(-current_p2.coef, current_p2.exp)
current_p2 = current_p2.next
return result
```
以上代码中,`add` 函数和 `sub` 函数分别实现了多项式的加法和减法,返回一个新的多项式。在循环中,比较两个多项式当前单项式的指数大小,如果相同则将系数相加(或相减),否则插入指数较大的单项式。最后,如果有一个多项式已经遍历完,则将另一个多项式的剩余单项式全部插入到结果多项式中。
使用示例:
```python
p1 = Polynomial() # 2x^3+3x^2-4x+1
p1.insert(2, 3)
p1.insert(3, 2)
p1.insert(-4, 1)
p1.insert(1, 0)
p2 = Polynomial() # -x^2+2x+1
p2.insert(-1, 2)
p2.insert(2, 1)
p2.insert(1, 0)
p3 = add(p1, p2) # 2x^3+2x^2-2x+2
print(p3) # 2x^3+2x^2-2x+2
p4 = sub(p1, p2) # 2x^3+4x^2-6x
print(p4) # 2x^3+4x^2-6x
```
阅读全文