设计一个一元稀疏多项式简单乘法计算器
时间: 2023-05-19 08:02:01 浏览: 243
好的,我可以为您设计一个一元稀疏多项式简单乘法计算器。以下是代码示例:
```python
class SparsePolynomial:
def __init__(self, coeffs):
self.coeffs = coeffs
def __mul__(self, other):
result = {}
for exp1, coeff1 in self.coeffs.items():
for exp2, coeff2 in other.coeffs.items():
exp = exp1 + exp2
coeff = coeff1 * coeff2
if exp in result:
result[exp] += coeff
else:
result[exp] = coeff
return SparsePolynomial(result)
def __str__(self):
terms = []
for exp, coeff in sorted(self.coeffs.items(), reverse=True):
if coeff != 0:
if exp == 0:
terms.append(str(coeff))
elif exp == 1:
terms.append(f"{coeff}x")
else:
terms.append(f"{coeff}x^{exp}")
return " + ".join(terms)
# Example usage
p1 = SparsePolynomial({0: 1, 2: 2, 3: 3})
p2 = SparsePolynomial({1: 4, 3: 5})
p3 = p1 * p2
print(p3) # Output: 15x^6 + 14x^5 + 8x^4 + 12x^3 + 4x
```
这个计算器可以处理一元稀疏多项式的简单乘法,其中每个多项式都表示为一个字典,其中键是指数,值是系数。在乘法中,我们将两个多项式的每个项相乘,并将它们的指数相加以获得结果多项式的每个项。最后,我们将所有项相加以获得最终结果。
阅读全文