Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除额外空间时使用内存_Python_Algorithm_Memory - Fatal编程技术网

Python 删除额外空间时使用内存

Python 删除额外空间时使用内存,python,algorithm,memory,Python,Algorithm,Memory,我需要删除字符串中的多余空格。我需要使用O(1)内存。是否可以不使用列表,因为列表使用的内存比字符串多(我已经用sys.getsizeof()检查过了),或者当我使用split()时,我仍然使用O(1)内存 有密码 s = input() s = s.split('_') s = list(filter(lambda a: a != '', s)) print('_'.join(s)) 我通常会这样做,以消除额外的空间 text=''.join(text.split()).strip() 不

我需要删除字符串中的多余空格。我需要使用O(1)内存。是否可以不使用列表,因为列表使用的内存比字符串多(我已经用
sys.getsizeof()
检查过了),或者当我使用
split()
时,我仍然使用O(1)内存

有密码

s = input()
s = s.split('_')
s = list(filter(lambda a: a != '', s))
print('_'.join(s))

我通常会这样做,以消除额外的空间

text=''.join(text.split()).strip()
不过,如果不想使用list,可以使用regex

重新导入
text=re.sub(r'{2,}','',text).strip()

请使用您尝试过的代码更新您的问题。您可以编辑问题并添加代码:)事实上,我需要删除额外的小写字符串。在python中,字符串是不可变的,因此删除空格将生成与原始字符串长度相当的新字符串。这使得不可能在O(1)空间中解决此问题。有没有办法检查这是否为
O(1)
?第二种方法似乎满足条件并使用O(1)存储器。您如何确定?它在时间或空间上不是O(1)。这是O(n)时间,O(n)空间(没有比这更有效的解决方案了)。