gpt4 book ai didi

Python while循环速度

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:18 25 4
gpt4 key购买 nike

如果有人可以向我解释为什么下面的代码有这么多额外的开销,我会很高兴。在 100k 次迭代时,两种情况下的速度都相同(2.2 秒)。当增加到 1E6 次迭代时,案例“B”永远不会完成,而案例“A”只需要 29 秒。

案例“A”

while n is not 1:
foo

案例“B”

while n > 1:
foo

如果有帮助,请完整代码

def coll(n):
count = 0
# while n is not 1:
while n > 1:
count += 1
if not n % 2:
n /= 2
else:
n = 3*n + 1
return count

for x in range(1,100000):
count = coll(x)

最佳答案

首先,你应该使用n > 1或者n != 1,而不是n is not 1。后者有效的事实是一个实现细节,显然它不适合你。

它不工作的原因是因为在你的代码中有 x 的值导致 Collat​​z 序列超过 sys.maxint 的值,它变成 n 转换为 long。然后,即使它最终回到 1,它实际上也是 1Llong,而不是 int

尝试使用 while n is not 1 and repr(n) != '1L':,它会按你预期的那样工作。但是不要那样做;只需使用 n > 1n != 1

关于Python while循环速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32292157/

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