Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the lambda function for a function that depends on the input

Tags:

python

lambda

As an input, I have a list of nonnegative whole numbers which are supposed to be the coefficients of a polynomial. But I also want to evaluate the polynomial for a certain number x.

For example:

If we have L=[2,3,1] as an input and x=42 we get 2x^2+3x+1=3655 What I want is for example:

>>>p=polynomial([2,3,1])
>>>p(O)
1 
>>>p(42)
>>>3655

I guess I have to make use of the lambda function somehow, and I do know how it works for two variables on a given function, but in this case the function depends on my input.

def polynomial(coef):
coef=coef[::-1]
for i in range(len(coef)):
    p=lambda x: coef[i]*x**i
    p+=p
return lambda x: p

This is of course absolute nonsense, as I cannot add up one lambda function to another, but this is what my approaching "intuition" is.

Some hints are much appreciated.

like image 806
Tesla Avatar asked May 22 '26 01:05

Tesla


1 Answers

The most obvious pythonic solution (using a closure - with a lambda or (preferably) a named inner function) has already been posted, but for the sake of completeness I'll add the other pythonic solution - the OO version using a custom callable class:

class Polynomial(object):
    def __init__(self, coef):
        self.coef = coef

    def __call__(self, x):
        n = len(self.coef) - 1
        return sum(c * x ** (n - i) for (i, c) in enumerate(self.coef))

p = Polynomial([2,3,1])
print p(0)
print p(42)
like image 145
bruno desthuilliers Avatar answered May 24 '26 15:05

bruno desthuilliers