gpt4 book ai didi

python - 在 python 中找到阶乘的最佳方法?

转载 作者:太空宇宙 更新时间:2023-11-03 12:16:11 25 4
gpt4 key购买 nike

我正在研究阶乘的速度。但我只使用两种方式,

import timeit

def fact(N):
B = N
while N > 1:
B = B * (N-1)
N = N-1
return B

def fact1(N):
B = 1
for i in range(1, N+1):
B = B * i
return B


print timeit.timeit('fact(5)', setup="from __main__ import fact"), fact(5)
print timeit.timeit('fact1(5)', setup="from __main__ import fact1"), fact1(5)

这是输出,

0.540276050568 120
0.654400110245 120

从我观察到的上面的代码,

  1. 虽然花费的时间比

我的问题是,

是在 python 中查找阶乘的最佳方法吗?

最佳答案

如果您正在寻找最好的,为什么不使用数学模块中提供的那个呢?

>>> import math
>>> math.factorial
<built-in function factorial>
>>> math.factorial(10)
3628800

以及我机器上的时间比较:

>>> print timeit.timeit('fact(5)', setup="from __main__ import fact"), fact(5)
0.840167045593 120
>>> print timeit.timeit('fact1(5)', setup="from __main__ import fact1"), fact1(5)
1.04350399971 120
>>> print timeit.timeit('factorial(5)', setup="from math import factorial")
0.149857997894

我们看到内置函数明显优于您提出的任何一个纯 Python 变体。

关于python - 在 python 中找到阶乘的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20604185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com