4

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!

1
  • 1
    If x is global, you need to explicitly tell Python that via global x. Commented Oct 29, 2016 at 1:18

2 Answers 2

8

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))) 
Sign up to request clarification or add additional context in comments.

5 Comments

It does indeed what I want, thanks. But I am still confused: The return of inner basically returns the setup so that once x is given the inner function can be solved. Is that correct? If so, how does general_poly(L) know that the x is coming after the def of general_poly? Because inner is def as inner(x)?
Yes, general_poly is a function of one param (L) that is returning a function that takes one parameter (x). Obviously the actual names of the parameters are immaterial.
The fact L is still accessible to inner() is called a closure.
Why would you want to rewrite inner as a lambda function??
Because the function is now just a one-liner and the fact there is no real value in giving the function a name, given you are just returning it. It's a matter of style, and I'm okay with others having a different opinion.
0
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.