Search code examples
pythonpython-3.xrecursionfactorial

How to implement a recursive function using lambda expressions


My task is to implement the factorial function using just a lambda expression. Here's what I have tried

fact = lambda n: if n == 0 return 1 else ...

I'm stuck!

Edit: fix if statement syntax error

fact = lambda n: 1 if n == 0 else ...

I'm stuck again..

How to do it?


Solution

  • A simple approach is to use the name of the variable you assign the lambda into as the way to call the code recursively:

    >>> fact = lambda n: 1 if n <= 0 else n * fact(n - 1)
    >>> fact(10)
    3628800
    >>> 
    

    There are more complex solutions involving passing lambda expressions to lambda expressions or Y-combinators. Your approach was already doomed by the use of an if ... else ... statement. A lambda expression can only contain other expressions, not statements, so you'd need to use the ... if ... else ... expression syntax instead.