1

I am trying to write a python function(al), which would generate a series, for example

   f(x) = 1 + x + x^2 + ... + x^n

given number of terms in the series. (Remember, the above is only an example of one such series.) I could do it to some extent as follows

def addTwoFunctions(f, g):
    return lambda x : f(x) + g(x)

It works okay if I now do it the dumb way:

// initialize h as a function
h = lambda x : 0*x

print h(2)                            # output = 0 

// first term in the series "1"
g = lambda x : x**0
h = addTwoFunctions(h, g)
print h(2)                            # output = 1

// second term  "x"
g = lambda x : x**1
h = addTwoFunctions(h, g)
print h(2)                            # output = 3

// third term "x^2"
g = lambda x : x**2
h = addTwoFunctions(h, g)
print h(2)                            # output = 7

This creates correct outputs (as shown with the comments). However if I put it in a for loop

print h(2)

for i in range(3) :
    g = lambda x: x**i
    h = addTwoFunctions(h,g)
    print h(2)
    pass

It generates output as

 0
 1
 4
 12

as if the function h gets doubled at each entry in the for loop. Am I doing something wrong here?

Thanks in advance, Nikhil

Nikhil J Joshi
  • 1,177
  • 2
  • 12
  • 25
  • I answered basically the exact same question earlier today ... http://stackoverflow.com/questions/17192226/strange-behavior-with-lamba-getattrobj-x-inside-a-list/17192263#17192263 – mgilson Jun 19 '13 at 14:05
  • @mgilson: and it has been answered many times before. we need a good dupe target. – Martijn Pieters Jun 19 '13 at 14:05
  • @MartijnPieters -- I know. But twice in a day isn't quite so common ;-) – mgilson Jun 19 '13 at 14:06
  • lambdas are just one-expression anonymous functions, so the same principles apply; `i` is looked up when the lambda is *called*, not when it is defined. – Martijn Pieters Jun 19 '13 at 14:07
  • aah... Thanks a lot you guys. I did know this caveat of lambdas, I just forgot to look at that "i" :p... Thanks once again! @mgilson, +1'd your answer at the link! – Nikhil J Joshi Jun 19 '13 at 14:12
  • and now I am stumped :(... I now don't see an obvious way to generate such a series :( – Nikhil J Joshi Jun 19 '13 at 14:16
  • @NikhilJJoshi: use a keyword argument to bind the `i` at definition time: `g = Functional(lambda x, i=i: x**i)` – Martijn Pieters Jun 19 '13 at 14:26

0 Answers0