每日一练 no.9

版权声明:本文为博主原创文章,如若转载请注明出处 https://blog.csdn.net/tonydz0523/article/details/83714013

问题:

求1+2!+3!+…+20!的和

解答:

方法一:
使用for循环:

n = 0
s = 0
t = 1
for n in range(1,21):
    t *= n
    s += t
print(s)

方法二:
构建函数,使用map,reduce(注意:python3的reduce函数在functools中)

from functools import reduce
l = range(1,21)
def factorial(x):
    lt = range(1, x+1)
    r = reduce(lambda x,y: x*y ,lt)
    return r
s = sum(map(factorial,l))
print (s)

方法三:
使用 math包 中的阶乘函数

from math import factorial
l = range(1,21)
s = sum(map(factorial,l))
print(s)

或是numpy中的

import numpy as np
l = range(1,21)
s = sum(map(np.math.factorial,l))
print(s)

猜你喜欢

转载自blog.csdn.net/tonydz0523/article/details/83714013
今日推荐