UpmostScarab
UpmostScarab

Reputation: 985

Sum of n lambda functions

I have a list of lambda functions. Lets say this one

l = [lambda x:x**i for i in range(n)]

For every n I need to be able to sum them so I'd have a function like this:

f = lambda x: x + x**2 + x**3 + ... + x**n

Is there any way?

Edit: I wasn't clear. I don't know anything about that functions.

Upvotes: 2

Views: 4588

Answers (5)

Sheikh
Sheikh

Reputation: 1

n=5  
xpower=[]  
for i in range(n):  
    xpower.insert(i, i+1)  
    print(i,xpower)  
f = lambda x, xpower: sum(x**xpower[i] for i in range(len(xpower)))  
print("Example with n=5, x=2:"," ", f(2,xpower))  

Upvotes: 0

YOBA
YOBA

Reputation: 2807

f = lambda x,n: sum( x**i for i in range(n) )

print f(3,4)

>> 40

Upvotes: 2

advance512
advance512

Reputation: 1358

Is this the solution you're looking for?

Python 3.x:

n = 5
g = lambda y: sum(  f(y) for f in (lambda x: x**i for i in range(n))  )
print(g(5)) # 781

Python 2.x:

n = 5
g = lambda y: sum(  f(y) for f in (lambda x: x**i for i in xrange(n))  )
print g(5) # 781

Upvotes: 3

Tom Karzes
Tom Karzes

Reputation: 24052

The simplest way to do this is to avoid creating the list of lambda functions, and to instead sum over a single function. Assuming you've defined x and n, you can do:

f = lambda x, i: x**i
sum(f(x, i) for i in range(n))

In your original example, you have actually created a closure, so your lambda functions do not do what you think they do. Instead, they are all identical, since they all use the final value of i in the closure. That is certainly not what you intended.

Upvotes: 0

Rory Daulton
Rory Daulton

Reputation: 22544

If you mean a finite sum, up to x**n, use the mathematical shortcut

f = lambda x: (x**(n+1) - 1) / (x - 1) if x != 1 else n

Upvotes: 3

Related Questions