this is the solution to a problem I'm working on (learning Python), but even the solution is giving me an error.
Here's the code:
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
This is the solution given to me, but when I use the following code to call the function:
poly1 = (-13.39)
print compute_deriv(poly1)
I get
TypeError: object of type 'float' has no len()
I've tried a couple different things inside the if statement (since this code only breaks when len(poly)
is < 2;
I tried poly_deriv.append(0.0)
and return poly_deriv
, for example.
I'm guessing there's a typo in the solution, and they intended it to be a one element collection.
poly1 = (-13.39,)
Or
poly1 = [-13.39]
The way they have it right now, it's a single float rather than a collection containing one float. (-13.39)
is syntactically equivalent to just -13.39
with no parentheses.
The line poly1 = (-13.39)
isn't a tuple. Python reads this as a parenthetical operation not a so your variable is simply a number. Try a more explicit definition instead:
poly1 = tuple(-13.39)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With