写一下一元稀疏多项式代码
时间: 2023-05-27 17:07:14 浏览: 102
这是一个一元稀疏多项式的代码,用于存储和操作一元稀疏多项式。
```
class Polynomial:
def __init__(self):
self.poly = {}
def add_term(self, coeff, exp):
if coeff != 0:
self.poly[exp] = coeff
def __add__(self, other):
result = Polynomial()
for exp in self.poly:
result.add_term(self.poly[exp], exp)
for exp in other.poly:
if exp in result.poly:
result.poly[exp] += other.poly[exp]
else:
result.add_term(other.poly[exp], exp)
return result
def __sub__(self, other):
result = Polynomial()
for exp in self.poly:
result.add_term(self.poly[exp], exp)
for exp in other.poly:
if exp in result.poly:
result.poly[exp] -= other.poly[exp]
else:
result.add_term(-other.poly[exp], exp)
return result
def __mul__(self, other):
result = Polynomial()
for exp1 in self.poly:
for exp2 in other.poly:
coeff = self.poly[exp1] * other.poly[exp2]
exp = exp1 + exp2
if exp in result.poly:
result.poly[exp] += coeff
else:
result.add_term(coeff, exp)
return result
def evaluate(self, x):
result = 0
for exp in self.poly:
result += self.poly[exp] * (x ** exp)
return result
def __str__(self):
terms = []
for exp in sorted(self.poly.keys(), reverse=True):
coeff = self.poly[exp]
if coeff > 0:
sign = '+'
elif coeff < 0:
sign = '-'
coeff = -coeff
else:
continue
if exp == 0:
term = '{}{}'.format(sign, coeff)
elif exp == 1:
term = '{}{}x'.format(sign, coeff)
else:
term = '{}{}x^{}'.format(sign, coeff, exp)
terms.append(term)
if not terms:
return '0'
else:
return ' '.join(terms)
```
这个代码定义了一个 `Polynomial` 类,其中每个多项式都是一个字典,存储了每个指数的系数。该类包含了一些方法,如:
- `add_term()` 方法:用于添加一个项,如果系数不为 0,则将该项添加到多项式中。
- `__add__()` 方法:用于多项式加法。
- `__sub__()` 方法:用于多项式减法。
- `__mul__()` 方法:用于多项式乘法。
- `evaluate()` 方法:用于计算多项式在给定值 `x` 处的值。
- `__str__()` 方法:用于将多项式转换为字符串。
这个代码可以用于处理一元稀疏多项式的加、减、乘、求值等操作。
阅读全文