如何从外部编写带有变量的函数?

How to write function with variable from the outside?

希望对你有所帮助。我正在寻找一种方法来编写一个稍后插入一个项目的函数。让我举个例子:

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

我想我可以在这里给 x 一个值,一旦我这样做 general_poly(L)(10) 它将被替换,以便 x = 10 但显然这并不容易。我必须更改/添加什么才能使我的功能正常工作?该函数如何知道乘法是 x?谢谢你们的帮助,伙计们!

您被要求 return 一个函数,但您 return 正在计算计算值:

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)))
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