gpt4 book ai didi

python - Lambda 函数无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:59 24 4
gpt4 key购买 nike

我正在尝试编写一个 lambda 函数来执行我已经使用 while 循环实现的相同程序,但我无法弄清楚如何使用 lambda 函数更正我当前的程序.在这里,我想将 4 乘以 n 的减少值。例如,3 应该像 4*3=12 那样工作,然后是 12*2=24,但是如果 n=3<,这里它总是用 3 乘以 4/。使用 while 循环,我编写了如下在 foo 函数中给出的程序。这不是阶乘;基本上,我想为 n 的不同值打印这个系列,例如:

n=1 ans=4,
n=2 ans=8,
n=3 ans=24,
n=4 ans=96,
n=5 ans= 480.

foo 函数中的逻辑正在生成此输出。

foo= lambda n: 4*n**~-n

def foo(n):
a=4
i=1
while i<=n:
a*=i
i+=1
return a
print(foo(7)) #20160

最佳答案

~unary bitwise运算符表示 NOT~x 等同于 -x - 1。让我们分解一下:

4*n**~-n == 4*3**~-3 == 4*3**(~-3) == 4*3**2 == 4*(3**2 ) == 4*9 == 36

你想要的是找到4 * factorial(n)。您可以导入 math 模块来执行此操作:

from math import factorial

def foo(n):
return 4 * factorial(n)

这将解释为:

from math import factorial

foo = lambda n: 4*factorial(n)

上述方法的问题在于 lambda 被创建为无名。当您想多次使用 lambda 时,使用它是违背他们的意图的。坚持这个功能。

关于python - Lambda 函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37934491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com