【发布时间】:2020-10-06 08:01:58
【问题描述】:
我开始编写一个小类,它应该在一个变量中表示多项式函数。我知道功能强大的 sympy 模块已经存在,但我认为放置几行代码而不是加载整个 sympy 模块更简单。主要原因是只是简单地使用了我不需要的抽象级别(即处理变量和环)。
这就是我所做的:
class Polynomial:
"""Class representing polynomials."""
def __init__(self, *coefficients):
self.coefficients = list(coefficients)
"""Coefficients of the polynomial in the order a_0,...a_n."""
def __repr__(self):
return "Polynomial(%r)" % self.coefficients
def __call__(self, x):
res = 0
for index, coeff in enumerate(self.coefficients):
res += coeff * x** index
return res
我还想实现__str___,其输出与 for 循环产生的输出相同:
res = ""
for index, coeff in enumerate(self.coefficients):
res += str(coeff) + "x^"+str(index)
首先,我希望像 "$r*x^%r" % enumerate(self.coefficients) 这样的东西可以工作,但事实并非如此。我尝试将enumerate(...) 转换为元组,但这也没有解决问题。
对于我可以用于__str__ 的pythonic 单行返回语句有什么想法吗?
【问题讨论】:
标签: python string string-formatting