How to write a function with a variable from the outside?

I hope you can help. I am looking for a way to write a function that inserts one element later. Let me show you an example:

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 
        """
        x = 1
        res = 0
        n = len(L)-1
        for e in range(len(L)):
            res += L[e]*x**n
            n -= 1
        return res

I thought I could just give a xvalue here, and as soon as I do general_poly(L)(10), it will be replaced so that x = 10, but apparently it is not so simple. What do I need to change / add for my function to work? How does a function know that multiplication is this x? Thanks for your help guys!

+4
source share
2 answers

You are prompted to return a function, but you are returning a computed 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

general_poly(L)(10) , , , , , , , :

L = [...]
fn = general_poly(L)
print(fn(10))
print(fn(3))

inner :

def general_poly(L):
    return lambda x: sum(e*x**n for n, e in enumerate(reversed(L)))
+8
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):
        L.reverse()
        return sum(e*x**L.index(e) for e in L)
    return inner
0

Source: https://habr.com/ru/post/1659240/


All Articles