这是我正在研究的问题的解决方案(学习Python),但即使是解决方案也给了我一个错误.
这是代码:
def compute_deriv(poly):
"""
Computes and returns the derivative of a polynomial function. If the
derivative is 0, returns [0.0].
Example:
>>> poly = [-13.39, 0.0, 17.5, 3.0, 1.0] # - 13.39 + 17.5x^2 + 3x^3 + x^4
>>> print compute_deriv(poly) # 35^x + 9x^2 + 4x^3
[0.0, 35.0, 9.0, 4.0]
poly: list of numbers, length > 0
returns: list of numbers
"""
poly_deriv = []
if len(poly) < 2:
return [0.0]
for j in xrange(1, len(poly)):
poly_deriv.append(float(j * poly[j]))
return poly_deriv
Run Code Online (Sandbox Code Playgroud)
这是给我的解决方案,但当我使用以下代码调用该函数时:
poly1 = (-13.39)
print compute_deriv(poly1)
Run Code Online (Sandbox Code Playgroud)
我明白了
TypeError: object of type 'float' has no len()
Run Code Online (Sandbox Code Playgroud)
我在if语句中尝试了几个不同的东西(因为这个代码只在len(poly)<2 时才会中断;
我试过poly_deriv.append(0.0)和return poly_deriv,例如.
我猜测解决方案中存在拼写错误,他们打算将其作为单元素集合.
poly1 = (-13.39,)
Run Code Online (Sandbox Code Playgroud)
要么
poly1 = [-13.39]
Run Code Online (Sandbox Code Playgroud)
他们现在拥有它的方式,它是一个浮动而不是包含一个浮点数的集合.(-13.39)语法上等同于-13.39没有括号.