Python 计算阶乘的函数是什么?
python 菜鸟,请大家赐教
Python 计算阶乘的函数是什么?
6 回复
自己写
Python里算阶乘,标准库math里就有现成的math.factorial()函数,直接调就行。
import math
# 计算5的阶乘
result = math.factorial(5)
print(result) # 输出: 120
如果你不想用库,自己写一个也很简单,用递归或者循环都行。比如用循环:
def factorial_iterative(n):
if n < 0:
raise ValueError("阶乘未定义负数")
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_iterative(5)) # 输出: 120
用递归写:
def factorial_recursive(n):
if n < 0:
raise ValueError("阶乘未定义负数")
if n <= 1:
return 1
return n * factorial_recursive(n - 1)
print(factorial_recursive(5)) # 输出: 120
简单说,直接用math.factorial()最省事。
from operator import mul
fac = lambda x: reduce(mul, range(1, x + 1))
import math
math.factorial(x)
4 楼正解。


