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