Abdalla Ismail
Abdalla Ismail

Reputation: 45

How to fix this ' float not iterable ' Error

I'm Solving the Problem set of MIT's introduction to programming.

def compute_deriv(poly):
    """
    Computes and returns the derivative of a polynomial function. If the
    derivative is 0, returns (0.0,).
    """

    der = ()
    for ele in poly :
        if poly.index(ele) == 0 :
            continue
        else:
            der += tuple(ele*float(poly.index(ele)))
    return der

poly = (-13.39, 0.0, 17.5, 3.0, 1.0)    # x^4 + 3x^3 + 17.5x^2 - 13.39

print compute_deriv(poly)

why the program is trying to iterate over this line? and return the error not iterable? it shouldn't be so

der += tuple(ele*float(poly.index(ele)))

Upvotes: 2

Views: 60

Answers (1)

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

Python is interpreting

tuple(ele*float(poly.index(ele)))

as a cast, rather than as a wrapper. You're giving it one argument, and it's assuming that that argument is an iterable object that you want to reformat into a tuple. In fact, you actually want to create a one-element tuple containing the object. This can happen with lists and sets, too, and I suspect if you did either of the following:

list(ele*float(poly.index(ele)))
set(ele*float(poly.index(ele)))

you'd see the same error as you're currently experiencing.


The simplest solution to this is to simply use a tuple literal, rather than the tuple() function:

der += (ele*float(poly.index(ele)),)

(for clarity, (value,) is the syntax for a 1-element tuple, because just parentheses would be ambiguous. If you want to be maximally clear, you could just use a list instead most of the time - a list literal is just [] and a set literal is {})

Upvotes: 2

Related Questions