pyhon数据结构一元多项式计算
时间: 2024-06-20 15:01:32 浏览: 109
在Python中,一元多项式通常表示为`Polynomial`对象,其计算可以通过定义一个类来实现,该类包含系数列表和相关的运算方法。以下是一个简单的实现,使用列表存储系数,并包含加法、乘法等基本操作:
```python
class Polynomial:
def __init__(self, coefficients=None):
if coefficients is None:
self.coefficients =
else:
self.coefficients = list(coefficients)
def __add__(self, other):
if isinstance(other, Polynomial):
result_coefficients = [a + b for a, b in zip(self.coefficients, other.coefficients)]
result_coefficients.extend([c for c in (self.coefficients[len(other):] or other.coefficients[len(self):])])
return Polynomial(result_coefficients)
else:
raise TypeError("Can only add another polynomial")
def __mul__(self, other):
if isinstance(other, int) or isinstance(other, float):
result_coefficients = [coeff * other for coeff in self.coefficients]
return Polynomial(result_coefficients)
elif isinstance(other, Polynomial):
result = * (len(self) + len(other) - 1)
for i, a in enumerate(self.coefficients):
for j, b in enumerate(other.coefficients):
result[i+j] += a*b
return Polynomial(result)
else:
raise TypeError("Can only multiply by a number or another polynomial")
def __repr__(self):
terms = ['+%.2f*x^%d' % (coeff, power) for power, coeff in enumerate(self.coefficients, start=1) if coeff != 0]
return ' '.join(terms) or '0'
# 示例
p1 = Polynomial([1, 2, 3])
p2 = Polynomial([4, 5, 6])
p_sum = p1 + p2 # 输出: 5x^1 + 7x^0
p_product = p1 * 2 # 输出: 2x^1 + 4x^0
```
阅读全文