Python lambda function to calculate factorial of a number

前端 未结 11 1299
误落风尘
误落风尘 2020-12-30 12:00

I have just started learning python. I came across lambda functions. On one of the problems, the author asked to write a one liner lambda function for factorial of a number.

11条回答
  •  独厮守ぢ
    2020-12-30 12:59

    Let's peel this one liner open like an onion.

    print (lambda b: (Y))(num)
    

    We are making an anonymous function (the keyword lambda means we're about to type a series of parameter names, then a colon, then a function that uses those parameters) and then pass it num to satisfy its one parameter.

       (lambda a, b: a(a, b))(X,b)
    

    Inside of the lambda, we define another lambda. Call this lambda Y. This one takes two parameters, a and b. a is called with a and b, so a is a callable that takes itself and one other parameter

                (lambda a, b: b*a(a, b-1) if b > 0 else 1
                ,
                b)
    

    These are the parameters to Y. The first one is a lambda function, call it X. We can see that X is the factorial function, and that the second parameter will become its number.

    That is, if we go up and look at Y, we can see that we will call:

    X(X, b)
    

    which will do

    b*X(X, b-1) if b > 0 else 1
    

    and call itself, forming the recursive part of factorial.

    And looking all the way back outside, we can see that b is num that we passed into the outermost lambda.

    num*X(X, b-1) if num > 0 else 1
    

    This is kind of confusing because it was written as a confusing one liner :)

提交回复
热议问题