Python lambda function to calculate factorial of a number

前端 未结 11 1316
误落风尘
误落风尘 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:43

    There are two hard parts about this function.
    1. lambda a, b: b*a(a, b-1) if b > 0 else 1.
    2. the "b" that's folowing 1.

    For 1, it's nothing more than:

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

    For 2, this b

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

    is actually this b:

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

    The reason is that it's not inside the definition of the second and third lambda, so it refers to the first b.

    After we apply num and strip off the outer function:

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

    It's just applying a function to a tuple, (lambda a, b: b*a(a, b-1) if b > 0 else 1, num)
    Let's call this tuple as (f, num) (f's def is above) Applying lambda a, b: a(a, b) on it, we get

    f(f, num).

    Suppose your num is 5.
    By definiton of f, it first evaluates to

    5 * f(f, 4)  
    

    Then to:

    5 * (4 * f(f, 3)) 
    

    All the way down to

    5 * (4 * (3 * (2 * (1 * f(f, 0)))))
    

    f(f, 0) goes to 1.

    5 * (4 * (3 * (2 * (1 * 1))))
    

    Here we go, the factorial of 5.

提交回复
热议问题