我的解决方案使用迭代,其中第 i 个元素是 x^i 的系数,所以对于 p(x) = 3*x^5 + 2*x^3 + x^2 + 5 em> 输入将是[5, 0, 1, 2, 0, 3]。导数是p'(x) = 15*x^4 + 6*x^2 + 2*x,所以预期结果应该是[0, 2, 6, 0, 15]。
>>> import itertools, operator
>>> coeff = [5, 0, 1, 2, 0, 3]
>>> print list(itertools.imap(operator.mul, itertools.islice(coeff, 1, None), itertools.count(1)))
[0, 2, 6, 0, 15]
更新:我想在这里使用迭代器和所有东西变得非常棘手,但结果证明我的解决方案比 GregS 的慢两倍多。有人可以解释一下这种缓慢是从哪里来的吗?
>>> print timeit.repeat("poly(coeff)", "poly = lambda coeff: [coeff[i] * i for i in range(1, len(coeff))]; coeff = [1, 0, 0, 5, 0, -29]")
[1.7786244418210748, 1.7956598059847046, 1.7500179643792024]
>>> print timeit.repeat("poly(coeff)", "import operator, itertools; poly = lambda coeff: list(itertools.imap(operator.mul, itertools.islice(coeff, 1, None), itertools.count(1))); coeff = [1, 0, 0, 5, 0, -29]")
[4.01759841913463, 4.152715700867423, 5.195021813889031]