在Python中,阶乘通常用 `n!` 表示,其中 `n` 是要计算阶乘的整数。阶乘 `n!` 是从 `1` 到 `n` 所有整数的乘积。例如,`5!` 表示 `5 * 4 * 3 * 2 * 1`,其结果是 `120`。
要计算一个数的阶乘,你可以使用以下方法之一:
递归方法
def factorial_recursive(n):
if n == 0:
return 1
else:
return n * factorial_recursive(n - 1)
循环方法(使用 `for` 循环):
def factorial_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
使用 `reduce()` 函数(从 `functools` 模块调用 `reduce()` 函数):
from functools import reduce
def factorial_reduce(n):
return reduce(lambda x, y: x * y, range(1, n + 1))
使用 `math.factorial()` 函数(Python 的内置 `math` 模块提供了一个 `factorial` 函数):
import math
def factorial_math(n):
return math.factorial(n)
选择哪种方法取决于你的具体需求和个人偏好