如何从外部写变量函数? [英] How to write function with variable from the outside?

查看:168
本文介绍了如何从外部写变量函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望你能帮上忙。我正在寻找一种方法来编写一个稍后插入一个项目的函数。让我告诉你一个例子:

pre $ def general_poly(L):

L,数字列表(n0,n1,n2,... nk)
返回一个函数,该函数应用于值x时,返回值
n0 * x ^ k + n1 * x ^( k-1)+ ... nk * x ^ 0

x = 1
res = 0
n = len(L)-1
for e (len(L)):
res + = L [e] * x ** n
n - = 1
return res

我认为我可以在这里给 x 一个值,一旦我做了 general_poly(L)(10)它会被替换,使得 x = 10 但显然并不那么容易。我必须更改/添加什么以便我的功能有效?函数如何知道乘法是 x ?感谢您的帮助,大家好!

解决方案

你被要求返回一个函数,但你要返回计算值: p>

  def general_poly(L):

L,数字列表(n0,n1, n2,... nk)
返回一个函数,当它应用于一个值x时,返回值
n0 * x ^ k + n1 * x ^(k-1)+ ... nk * x ^ 0

def inner(x):
res = 0
n = len(L)-1
L)):
res + = L [e] * x ** n
n - = 1
返回资源
返回内部

现在 general_poly(L)(10)会做你的期望,但它可能更有用如果将它赋值给一个值,可以多次调用它,例如:

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

您也可以重写 inner to:

  def general_poly(L):
return lambda x:sum(e * x ** n代表n,e代表枚举(反转(L)))


I hope you can help. I am looking for a way to write a function that inserts one item 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 x a value here and once I do general_poly(L)(10) it will be replaced so that x = 10 but apparently it is not that easy. What do I have to change / add so that my function works? How does the function know, that the multiplication is the x? Thanks for your help, guys!

解决方案

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.:

L = [...]
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 n, e in enumerate(reversed(L)))

这篇关于如何从外部写变量函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆