编写程序实现一元多项式的创建以及两个一元多项式相加和相乘的操作。
时间: 2024-11-12 17:31:35 浏览: 20
单链表实现一元多项式相乘.rar
5星 · 资源好评率100%
在编写程序实现一元多项式操作时,通常会使用数据结构来存储多项式的系数和对应的变量指数。这里我们可以使用列表或字典来表示多项式,其中键是指数,值是对应系数。以下是Python的一个简单示例:
```python
class Polynomial:
def __init__(self, coefficients={}):
self.coefficients = coefficients
def add(self, other):
result = {}
for exp, coef in self.coefficients.items():
if exp in other.coefficients:
result[exp] = coef + other.coefficients[exp]
else:
result[exp] = coef
for exp, coef in other.coefficients.items():
if exp not in self.coefficients:
result[exp] = coef
return Polynomial(result)
def multiply(self, other):
product = Polynomial()
for self_exp, self_coef in self.coefficients.items():
for other_exp, other_coef in other.coefficients.items():
if self_exp + other_exp in product.coefficients:
product.coefficients[self_exp + other_exp] += self_coef * other_coef
else:
product.coefficients[self_exp + other_exp] = self_coef * other_coef
return product
# 示例
p1 = Polynomial({0: 1, 2: 3, 3: 4}) # x^0 + 3x^2 + 4x^3
p2 = Polynomial({1: 5, 2: 6, 3: 7}) # 5x^1 + 6x^2 + 7x^3
add_result = p1.add(p2)
multiply_result = p1.multiply(p2)
print("Addition:", add_result.coefficients) # {0: 1, 1: 5, 2: 9, 3: 11}
print("Multiplication:", multiply_result.coefficients)
阅读全文