两个一元多项式的运算完整代码
时间: 2024-12-16 16:20:01 浏览: 4
在Python中,我们可以创建一个简单的类来表示一元多项式,并提供加法、减法和乘法操作。下面是一个基本的一元多项式类以及两个多项式相加和相乘的例子:
```python
class Polynomial:
def __init__(self, coefficients):
self.coefficients = coefficients
# 定义加法方法
def __add__(self, other):
if not isinstance(other, Polynomial):
raise ValueError("只能对多项式进行加法")
result = []
for i in range(max(len(self.coefficients), len(other.coefficients))):
term1 = self.coefficients[i] if i < len(self.coefficients) else 0
term2 = other.coefficients[i] if i < len(other.coefficients) else 0
result.append(term1 + term2)
return Polynomial(result)
# 定义乘法方法 (这里我们只展示一个简单版本,对于复杂项的处理可以更复杂)
def __mul__(self, other):
if not isinstance(other, Polynomial):
raise ValueError("只能对多项式进行乘法")
result_coefficients = [0] * (len(self.coefficients) + len(other.coefficients) - 1)
for i, c1 in enumerate(self.coefficients):
for j, c2 in enumerate(other.coefficients):
result_coefficients[i+j] += c1 * c2
return Polynomial(result_coefficients)
# 示例使用
p1 = Polynomial([2, 1, 0]) # 2x^2 + x
p2 = Polynomial([1, 3, 4]) # x + 3x^2 + 4x^3
# 加法
sum_poly = p1 + p2
print("Sum:", sum_poly.coefficients) # 输出: [3, 4, 4]
# 乘法 (简化示例)
product = p1 * p2
print("Product (simplified):", product.coefficients) # 输出: [2, 5, 8, 12]
阅读全文