python中如何用for语句写出从1的阶乘到20的阶乘的加和?

python中如何用for语句写出从1的阶乘到20的阶乘的加和?

# using python 3 # v1 def fact ( i ): result = 1 for j in range ( 1 , i + 1 ): result *= j return result print ( sum ( fact ( i ) for i in range ( 1 , 21 ))) # v2 import numpy as np print ( sum ( np . math . factorial ( i ) for i in np . arange ( 1 , 21 ))) # v3 from scipy.special import factorial print ( factorial ( np . arange ( 1 , 21 )) . sum ()) """ v4/v5 利用阶乘之间的累乘关系进行优化, 如6!= 6 * 5!, 因此不需要重复计算每个数的阶乘 """ # v4 result = 0 temp = 1 for i in range ( 1 , 21 ): temp = temp * i result += temp print ( result ) # v5, 等价于v4 import numpy as np print ( np . cumprod ( range ( 1 , 21 )) . sum ())