Skip to main content
 首页 » 编程设计

Python while循环速度

2025年05月04日15jyk

如果有人可以向我解释为什么下面的代码有这么多额外的开销,我会很高兴。在 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,它实际上也是 1L; long,而不是 int。

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