0

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?

4
  • The title and your question are not the same thing. Do you need to implement factorial with a lambda or do you need to do it with recursion using a lambda? Commented Jan 13, 2019 at 20:03
  • You can implement factorial using recursion. There is not a difference in what you're saying. Commented Jan 13, 2019 at 20:53
  • You can also implement it without recursion. An iterative approach is much better for this. For example: fact = lambda n: reduce(operator.mul, range(1,n+1)) Commented Jan 13, 2019 at 21:37
  • That's why I did title it "recursive" because I want the recursive implementation to showcase the use of lambda expressions in that case, but not the iterative one. Commented Jan 13, 2019 at 21:40

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah actually the "if statement I did" was a mistake i meant what you did. Thanks for your solution; I didn't know one can access the variable before it's finished being defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.