Python 将数字转换为元组和内存错误

Python 将数字转换为元组和内存错误,python,Python,因此,我必须使用自然数的定义将给定的数字n转换成一组元组。我知道了如何做到这一点,但是,如果我输入一个大的数字,如1000,它需要很长时间,并产生一个内存错误。我如何使代码运行得更快而不占用太多内存 output = [(),((),)] def n_to_tuple(n): if n < 0: return None if n == 0: return output[0] if n == 1: return outp

因此,我必须使用自然数的定义将给定的数字n转换成一组元组。我知道了如何做到这一点,但是,如果我输入一个大的数字,如1000,它需要很长时间,并产生一个内存错误。我如何使代码运行得更快而不占用太多内存

output = [(),((),)]
def n_to_tuple(n):
    if n < 0:
        return None
    if n == 0:
        return output[0]
    if n == 1:
        return output[1]
    if n < len(output):
        return output[n]
    while n >= len(output):
        output.append(tuple(output))
    return tuple(output[n])
output=[(),((),)]
定义n到n元组(n):
如果n<0:
一无所获
如果n==0:
返回输出[0]
如果n==1:
返回输出[1]
如果n=len(输出)时:
append(元组(输出))
返回元组(输出[n])

问题是,这个构造作为“数据”放入内存,因为当您执行联合步骤时,现有元组不会被复制/复制,只对它们进行引用。
作为中间步骤,这里是代码的一个缩减变体:

output = [()]
def n_to_tuple(n):
    if n < 0:
        return None
    if n < len(output):
        return output[n]
    while n >= len(output):
        output.append(tuple(output))
    return tuple(output[n])
正如您可以看到的那样,x-s和y-s突然无处不在,数据没有被复制/复制,而是被引用。这就是你的元组大列表如何放入内存的原因,因为这些元组彼此重复使用,最后有一个1001元素列表(这算不了什么),其中有1001个元组,其中一些元组引用了很多其他元组,但这只是内存中的一个标识符。我们所说的这种存储容量不足1兆字节

当你想要打印结果时,事情会发生根本性的变化,也就是当你的内存用完时。实际输出在此处以输入及其长度作为前缀:


所以字符串的长度在每个步骤中都是重复的(并得到一些额外的增加,但我们忽略这一部分)。这就是@Selcuk在写“
2^1000
真是个大数字”时的意思。比较一下:1G是
2^30
字节。

在我尝试时运行良好。
output.append(tuple(output))
?!?这就是将
output
的连续副本添加到自身,嵌套越来越深。这里的目标是什么?
2^1000
是一个非常大的数字。涉及到足够多的别名,因此所使用的内存量只会以二次方式增长,而不是以指数方式增长。这并不能提高效率——效率非常低——但对于小到1000的n,不应该有内存错误。@JohnColeman:哦,是的,如果您尝试以交互方式运行
n到tuple(1000)
,Python会尝试自动打印结果。那会引起一场回忆。
output = [[]]
def n_to_tuple(n):
    if n < 0:
        return None
    if n < len(output):
        return output[n]
    while n >= len(output):
        output.append(list(output))
    return list(output[n])

for i in range(5):
    print(n_to_tuple(i))

print()
output[0].append('x')

for i in range(5):
    print(n_to_tuple(i))

print()
output[1].append('y')

for i in range(5):
    print(n_to_tuple(i))
[]
[[]]
[[], [[]]]
[[], [[]], [[], [[]]]]
[[], [[]], [[], [[]]], [[], [[]], [[], [[]]]]]

['x']
[['x']]
[['x'], [['x']]]
[['x'], [['x']], [['x'], [['x']]]]
[['x'], [['x']], [['x'], [['x']]], [['x'], [['x']], [['x'], [['x']]]]]

['x']
[['x'], 'y']
[['x'], [['x'], 'y']]
[['x'], [['x'], 'y'], [['x'], [['x'], 'y']]]
[['x'], [['x'], 'y'], [['x'], [['x'], 'y']], [['x'], [['x'], 'y'], [['x'], [['x'], 'y']]]]
0: [2] ()
1: [5] ((),)
2:[11] ((), ((),))
3:[24] ((), ((),), ((), ((),)))
4:[50] ((), ((),), ((), ((),)), ((), ((),), ((), ((),))))
5:[102]
6:[206]