Let's peel this one liner open like an onion. Print reduce(lambda x, y: x * y, range(1, n + 1)) Print(recursive_lambda(lambda a, b: b * a(a, b - 1) if b > 0 Print(recursive_lambda(lambda self, x: x * self(self, x - 1) if x > 0 This can be generalized to recursive_lambda as long as you don't mind a(a, b - 1) instead of a(b - 1): recursive_lambda = (lambda func: lambda * args: func(func, * args)) It takes itself as its first argument, and the evaluation point as the second. This bit is the application of the factorial: = (lambda a, b: a(a, b))(, b) = lambda a, b: b*a(a, b-1) if b > 0 else 1 What is the formula of factorial in Python?. How do you use lambda function in factorial Python?.Method 2: Using Reduce Function & Lambda Expression.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |