【问题标题】:How to write a lambda function that performs a function on the integers from one to n where n is an integer?如何编写一个 lambda 函数,对从 1 到 n 的整数执行函数,其中 n 是整数?
【发布时间】:2019-10-03 09:28:27
【问题描述】:

编写一个名为 factorials_1_to_n 的 lambda 函数,用于计算从 1 到 n 的数字的阶乘。提示:使用您已经创建的函数阶乘。

我唯一能想到的就是在 lambda 函数中编写一个 for 循环,例如 .... for i in range(1,len(n)+1): factorial(i)...。但在 lambda 函数中不允许使用 for 循环。

def factorial(n):
product=n
while n!=1:
    product=product*(n-1)
    n=n-1
return(product)
y=factorial(4)
print(y)


factorials_1_to_n = lambda n: ????????
y=factorials_1_to_n(4)
print(y)

【问题讨论】:

标签: python


【解决方案1】:

我假设列表是可接受的结果类型

factorials_1_to_n = lambda n: [factorial(i+1) for i in range(n)]

i+1 用于计算它从 1 到 n,而不是从 0 到 n-1。

在 python 中查看list comprehension

【讨论】:

    猜你喜欢
    • 2013-11-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 2021-07-12
    • 2013-09-16
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    相关资源
    最近更新 更多