方法一:使用python内存方法reduce
from functools import reduce
def factorial(n): s = 0 if not isinstance(n ,int): raise TypeError elif n in (0, 1): return 1 else: for i in range(1, n+1): s = s + reduce(lambda x, y: x*y, range(1, i+1)) return s
方法二:循环
def factorial(n):
a = 0
if not isinstance(n, int):
raise TypeError
elif n in (0, 1):
return 1
else:
for i in range(1, n + 1):
s = 1
for j in range(1, i+1):
s = s * j
a = a + s
return a