0

Suppose I have a series of python function:

lam1 = lambda x: return x+1
lam2 = lambda x: return x+2
lam3 = lambda x: return x+3

And I would like to call them in this way:

x = lam1(x)
x = lam2(x)
x = lam3(x)

or so like this:

for lam in lams:
    x = lam(x)

This is helpful if I have a lot of functions to call, but this would have for loop. Do I have other way to do this without for loop?

coin cheung
  • 949
  • 2
  • 10
  • 25

1 Answers1

1

One of possible solutions is to simply use one function in another, like this:

>>> lam1 = lambda x: x+1
>>> lam2 = lambda x: lam1(x)+2
>>> lam3 = lambda x: lam2(x)+3
>>> lam3(1)
7

Although i don't understand why you would want exactly that and no loops. This solution has the drawback of limited amount of functions one would care to construct in that way. Alternatively you can make a loop to create those functions like:

>>> from functools import partial
>>> oldLam = lambda x: x
>>> newLam = lambda x,lam,c: lam(x) + c
>>> for i in range(5):
    oldLam = partial(newLam, lam = oldLam, c = i)


>>> oldLam(1)
11

Unless it is also an illegal case for you...

Piotr Kamoda
  • 956
  • 1
  • 9
  • 24