使用列表推导创建阶乘列表 [英] Create list of factorials using list comprehension
问题描述
我正在尝试建立前十个阶乘的列表
I'm trying to build a list of the first ten factorials
[1,1,2,6,24,120,720,5040,40320,362880]
仅使用列表理解.有可能吗?
using only list comprehension. Is that possible?
我不知道发电机或lambda
.
这是我的尝试,但我绝对知道为什么这是错误的:
Here's my attempt, but I absolutely know why it's wrong:
lst = [1] + [i for i in range(1,10)]
lst[1:10] = [lst[i-1] * i for i in range(1,10)]
print(lst)
推荐答案
只是为了好玩:
使用列表推导和辅助累加器重用先前计算的值的单线大型黑客攻击
One-liner mega-hack using list comprehension and an auxililary accumulator to reuse previously computed value
s=[]; s=[s[-1] for x in range(1,10) if not aux.append(x*s[-1] if aux else 1)]
结果:
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
注意:math.factorial
答案是元素随机的方式.这里速度更快,因为我们可以重用以前的结果.
note: The math.factorial
answer is the way when elements are random. Here it's faster because we can reuse previous results.
还有另一个缺点:需要将所有元素存储在list
中,因为python不允许if
且赋值与C一样.因此,我们必须追加到列表中,并对返回的None
取反,以便if
测试为True
There's also another drawback: the need to store all elements in a list
because python does not allow if
and assignment like C does. So we have to append to a list and negate the None
it returns so if
test is True
正如我所说:很有趣,但是仍然很简单.
As I said: fun, but still a hack.
这篇关于使用列表推导创建阶乘列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!