How to write function with variable from outside in python?

Published on Author Code Father

You are being asked to return a function but you are returning the calculated value:

def general_poly(L):
    """ 
    L, a list of numbers (n0, n1, n2, ... nk)
    Returns a function, which when applied to a value x, returns the value 
    n0 * x^k + n1 * x^(k-1) + ... nk * x^0 
    """
    def inner(x):
        res = 0
        n = len(L)-1
        for e in range(len(L)):
            res += L[e]*x**n
            n -= 1
        return res
    return inner

Now general_poly(L)(10) will do what you expect but it is probably more useful if you assign it to a value, so it can be called it multiple times, e.g.:

fn = general_poly(L)
print(fn(10))
print(fn(3))

You could also rewrite inner to:

def general_poly(L):
    return lambda x: sum(e*x**n for e, n in zip(L, range(len(L)-1, -1, -1)))

Comments

comments