菜鸟笔记
提升您的技术认知

python语言求1 3! 5! 7! 9! 50!的几种思路-ag真人游戏

有一道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

 

网站地图