在Python中,阶乘通常表示为 `n!`,其中 `n` 是你想要计算阶乘的正整数。阶乘的定义是 `n! = n * (n-1) * (n-2) * ... * 1`,并且 `0!` 和 `1!` 都等于 `1`。
递归方法
```python
def factorial_recursive(n):
if n == 0:
return 1
else:
return n * factorial_recursive(n-1)
循环方法
```python
def factorial_iterative(n):
result = 1
for i in range(1, n+1):
result *= i
return result
使用 `reduce` 函数
```python
from functools import reduce
def factorial_reduce(n):
return reduce(lambda x, y: x * y, range(1, n+1))
使用 `math` 模块的 `factorial` 函数
```python
import math
def factorial_math(n):
return math.factorial(n)
你可以根据你的需要选择合适的方法来计算阶乘。例如,如果你想计算 `5!`,你可以这样调用函数:
```python
print(factorial_recursive(5)) 输出: 120
print(factorial_iterative(5)) 输出: 120
print(factorial_reduce(5)) 输出: 120
print(factorial_math(5)) 输出: 120