Python Lambda函数计算数字的阶乘 [英] Python lambda function to calculate factorial of a number

查看:203
本文介绍了Python Lambda函数计算数字的阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习python.我遇到了lambda函数.关于其中一个问题,作者要求编写一个用于数字阶乘的线性内衬拉姆达函数.

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.

这是给出的解决方案:

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

我听不懂奇怪的语法. a(a,b)是什么意思?

I cannot understand the weird syntax. What does a(a,b) mean?

有人可以解释吗?

谢谢

推荐答案

阶乘本身几乎与您期望的一样.您可以推断a是...阶乘函数. b是实际参数.

The factorial itself is almost as you'd expect it. You infer that the a is... the factorial function. b is the actual parameter.

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

这是阶乘的应用:

<factorial-application> = (lambda a, b: a(a, b))(<factorial>, b)

a是阶乘函数本身.它以自己为第一个论点,而评估点为第二个论点.只要您不介意使用a(a, b - 1)代替a(b - 1),就可以将其推广到recursive_lambda:

a is the factorial function itself. It takes itself as its first argument, and the evaluation point as the second. 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))
print(recursive_lambda(lambda self, x: x * self(self, x - 1) if x > 0 else 1)(6))
# Or, using the function verbatim:
print(recursive_lambda(lambda a, b: b*a(a, b-1) if b > 0 else 1)(6))

所以我们有外面的部分:

So we have the outer part:

(lambda b: <factorial-application>)(num)

您看到的所有呼叫者必须通过的是评估点.

As you see all the caller has to pass is the evaluation point.

如果您实际上想要使用递归lambda,则可以

If you actually wanted to have a recursive lambda, you could just name the lambda:

fact = lambda x: 1 if x == 0 else x * fact(x-1)

如果没有,则可以使用一个简单的帮助程序功能.您会注意到ret是一个可以引用自身的lambda,这与之前的代码中没有lambda可以引用其自身的代码不同.

If not, you can use a simple helper function. You'll notice that ret is a lambda that can refer to itself, unlike in the previous code where no lambda could refer to itself.

def recursive_lambda(func):
    def ret(*args):
        return func(ret, *args)
    return ret

print(recursive_lambda(lambda factorial, x: x * factorial(x - 1) if x > 1 else 1)(6))  # 720

两种方式都不必求助于将lambda传递给自身的荒谬手段.

Both ways you don't have to resort to ridiculous means of passing the lambda to itself.

这篇关于Python Lambda函数计算数字的阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆