code_junkie

Can a lambda function call itself recursively in Python

Nov 13th, 2011
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. fact = lambda x: 1 if x == 0 else x * fact(x-1)
  2.  
  3. fact = lambda x: x == 0 and 1 or x * fact(x-1)
  4.  
  5. >>> map(lambda n: (lambda f, *a: f(f, *a))(lambda rec, n: 1 if n == 0 else n*rec(rec, n-1), n), range(10))
  6. [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
  7.  
  8. # helper function
  9. def recursive(f, *p, **kw):
  10. return f(f, *p, **kw)
  11.  
  12. def fib(n):
  13. # The rec parameter will be the lambda function itself
  14. return recursive((lambda rec, n: rec(rec, n-1) + rec(rec, n-2) if n>1 else 1), n)
  15.  
  16. # using map since we already started to do black functional programming magic
  17. print map(fib, range(10))
  18.  
  19. (lambda v: (lambda n: n * __import__('types').FunctionType(
  20. __import__('inspect').stack()[0][0].f_code,
  21. dict(__import__=__import__, dict=dict)
  22. )(n - 1) if n > 1 else 1)(v))(5)
Add Comment
Please, Sign In to add comment