使用普通的for循环
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(factorial(5)) 输出:120
使用`reduce()`函数
from functools import reduce
def factorial(n):
return reduce(lambda x, y: x * y, range(1, n + 1))
print(factorial(5)) 输出:120
使用`math.factorial()`函数
import math
def factorial(n):
return math.factorial(n)
print(factorial(5)) 输出:120
使用递归函数
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) 输出:120
使用`numpy.math.factorial()`函数(需要安装`numpy`库):
import numpy
def factorial(n):
return numpy.math.factorial(n)
print(factorial(5)) 输出:120
以上是计算阶乘的几种常见方法。你可以根据自己的需要选择合适的方法。