设计一个一元稀疏多项式的简单计算器
时间: 2024-10-25 21:12:46 浏览: 23
设计一个一元稀疏多项式计算器,我们可以将其视为由一组系数和对应的变量指数构成的数据结构,例如`SparsePolynomial`。这种数据结构只存储非零项,可以提高空间效率。以下是一个简单的Python类实现:
```python
class Term:
def __init__(self, coefficient, exponent):
self.coefficient = coefficient
self.exponent = exponent
class SparsePolynomial:
def __init__(self):
self.terms = []
def add_term(self, coefficient, exponent):
if coefficient != 0:
term = Term(coefficient, exponent)
self.terms.append(term)
def evaluate(self, x):
result = 0
for term in self.terms:
result += term.coefficient * (x ** term.exponent)
return result
def degree(self):
return max([term.exponent for term in self.terms if term.coefficient != 0])
# 示例用法
polynomial = SparsePolynomial()
polynomial.add_term(3, 2) # 3x^2
polynomial.add_term(5, 1) # 5x
polynomial.evaluate(2) # 返回 34 (因为 3*2^2 + 5*2 = 34)
#
阅读全文