这两个函数以基本相同的方式计算相同的东西(整数的数量,使得相关的 Collatz 序列的长度不大于 n)。唯一的区别是第一个只使用集合,而第二个使用集合和列表。
第二个泄漏内存(至少在 Python 3.2 的 IDLE 中),第一个没有,我不知道为什么。我尝试了一些“技巧”(例如添加del
语句),但似乎没有任何帮助(这并不奇怪,这些技巧应该没用)。
我将感谢任何可以帮助我了解发生了什么的人。
如果您想测试代码,您可能应该使用n
55 到 65 范围内的值,任何高于 75 的值几乎肯定会导致(完全预期的)内存错误。
def disk(n):
"""Uses sets for explored, current and to_explore. Does not leak."""
explored = set()
current = {1}
for i in range(n):
to_explore = set()
for x in current:
if not (x-1) % 3 and ((x-1)//3) % 2 and not ((x-1)//3) in explored:
to_explore.add((x-1)//3)
if not 2*x in explored:
to_explore.add(2*x)
explored.update(current)
current = to_explore
return len(explored)
def disk_2(n):
"""Does exactly the same thing, but Uses a set for explored and lists for
current and to_explore.
Leaks (like a sieve :))
"""
explored = set()
current = [1]
for i in range(n):
to_explore = []
for x in current:
if not (x-1) % 3 and ((x-1)//3) % 2 and not ((x-1)//3) in explored:
to_explore.append((x-1)//3)
if not 2*x in explored:
to_explore.append(2*x)
explored.update(current)
current = to_explore
return len(explored)
编辑:在使用解释器的交互模式(没有 IDLE)时也会发生这种情况,但在直接从终端运行脚本时不会发生这种情况(在这种情况下,内存使用在函数返回后的某个时间或尽快恢复正常因为有一个明确的调用gc.collect()
)。