Hello, I need your help understanding lambda (and doing it a better way without).
f = lambda x : x*x # this is a list of functions [f for y in range(1,5)] [f for y in range(1,5)][0](2) # returns 4, as expected # ok now I want a list like # [x^2, 2*x^2, 3*x^2,...] [f*y for y in range(5)] # this causes an unsupported operand type because it cannot multiply a function and int # the idea is now to give the definition of the multiplication of functions and integers # (f * c)(xx) := f(x)*c [lambda xx: f(xx)*y for y in range(1,5)][0](1) # returns 4 # I would expect 1*x*x = 1 # Where is my mistake and what would be the correct way to do this without lambdas? If you are interested in the reason for the code: approxFunction gets a function and a list of x-values. It computes func on these points and returns an interpolating polynomial. (this form of interpolation is often not stable, the code demonstrates this) def lagrangeBase(i, points): """returns the i-th lagrange polynomial on the nodes points (list of xj) In Symbolic notation the result should be lagrangeBase(x)=\Pi_{j=0, j\ne i} (x-xj)/(xi-xj) """ xi = points[i] # all points without xi nums = [points[x] for x in range(len(points)) if x!=i ] # unsupported operand type * for functions, therefore the lambda xx # what is the proper way to do this ? return reduce(lambda a,b: lambda xx: a(xx)*b(xx) , map(lambda xj: lambda x: (x-xj)/(xi-xj), nums)) def approxFunction(func, points): """this returns an approximation polynomial for func on the nodes points \Sum lagrangeBase(x_i) func(x_i) """ funcValues = [func(x) for x in points] # this is the problem mentioned above # sumTerms = [lambda xx: lagrangeBase(i, points)(xx)*funcValues[i] for i in range(len(points))] # this works sumTerms = map(lambda i: lambda xx : lagrangeBase(i, points)(xx) * funcValues[i], range(len(points))) return reduce(lambda a,b: lambda xx: a(xx)+b(xx), sumTerms) I am using Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 0.6.13 -- An enhanced Interactive Python. Many thanks Daniel -- http://mail.python.org/mailman/listinfo/python-list