sch*_*der 173
最简单的方法:math.factorial(x)(2.6及以上版本).
如果你想/必须自己写,请使用类似的东西
import math
math.factorial(1000)
Run Code Online (Sandbox Code Playgroud)
或更具可读性的东西:
def factorial(n):
fact = 1
for num in range(2, n + 1):
fact *= num
return fact
Run Code Online (Sandbox Code Playgroud)
一如既往,谷歌是你的朋友;)
Jor*_*ril 113
在Python 2.6及更高版本中,尝试:
import math
math.factorial(n)
Run Code Online (Sandbox Code Playgroud)
小智 24
没有必要,因为这是一个老线程.但我在这里做的是另一种使用while循环计算整数阶乘的方法.
def factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
Run Code Online (Sandbox Code Playgroud)
Tad*_*eck 18
最短也可能是最快的解决方案是:
from math import factorial
print factorial(1000)
Run Code Online (Sandbox Code Playgroud)
您还可以构建自己的解决方案.一般来说,你有两种方法.最适合我的是:
from itertools import imap
def factorial(x):
return reduce(long.__mul__, imap(long, xrange(1, x + 1)))
print factorial(1000)
Run Code Online (Sandbox Code Playgroud)
(当结果变为时,它也适用于更大的数字long
)
实现同样的第二种方式是:
def factorial(x):
result = 1
for i in xrange(2, x + 1):
result *= i
return result
print factorial(1000)
Run Code Online (Sandbox Code Playgroud)
小智 7
def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1)
Run Code Online (Sandbox Code Playgroud)
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
Run Code Online (Sandbox Code Playgroud)
cProfile.run('fact(126000)')
Run Code Online (Sandbox Code Playgroud)
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
Run Code Online (Sandbox Code Playgroud)
使用堆栈很方便(就像递归调用一样),但它是有代价的:存储详细信息可能会占用大量内存。
如果堆栈很高,则意味着计算机存储了大量有关函数调用的信息。
该方法仅占用常量内存(如迭代)。
def fact(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
Run Code Online (Sandbox Code Playgroud)
cProfile.run('fact(126000)')
Run Code Online (Sandbox Code Playgroud)
cProfile.run('fact(126000)')
Run Code Online (Sandbox Code Playgroud)
def fact(n):
return math.factorial(n)
Run Code Online (Sandbox Code Playgroud)
cProfile.run('fact(126000)')
Run Code Online (Sandbox Code Playgroud)
4 function calls in 5.164 seconds
Run Code Online (Sandbox Code Playgroud)
def fact(n):
f = 1
for i in range(1, n + 1):
f *= i
return f
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Python2.5或更早的尝试
from operator import mul
def factorial(n):
return reduce(mul, range(1,n+1))
Run Code Online (Sandbox Code Playgroud)
对于较新的Python,数学模块中有因子,如此处的其他答案所示