Python语言求1+3!+5!+7!+9!+50!的几种思路

有一道Python面试题,求和1+3!+5!+7!+9!+50!

方法一: 常规思路 

L = [1, 3, 5, 7, 9, 50]


def func(n):
    if n == 1:
        return 1
    else:
        return n * func(n-1)

total = 0

for i in L:
    total = total + func(i)
print(total)

方法二: 递归求和

>>> def func(n):
...     return 1 if n == 1 else n * func(n-1)
>>> sum([func(i) for i in [1, 3, 5, 7, 9, 50]])
30414093201713378043612608166064768844377641568960512000000368047L

方法三: 函数编程

>>> from functools import reduce
>>> sum([reduce(lambda x,y:x*y, range(1, i+1)) for i in list(range(1, 10, 2)) + [50]])
30414093201713378043612608166064768844377641568960512000000368047L

方法四: 借助模块

>>> from scipy.special import factorial
>>> sum(factorial([1, 3, 5, 7, 9, 50], exact=True))
30414093201713378043612608166064768844377641568960512000000368047L

 

你可能感兴趣的:(【编程语言】)