Traceback (most recent call last):
File "/run-1341144766-1067082874/solution.py", line 27, in
main()
File "/run-1341144766-1067082874/solution.py", line 11, in main
if len(s[i:j+1]) > 0:
MemoryError
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/apport_python_hook.py", line 64, in apport_excepthook
from apport.fileutils import likely_packaged, get_recent_crashes
File "/usr/lib/python2.7/dist-packages/apport/__init__.py", line 1, in
from apport.report import Report
MemoryError
Original exception was:
Traceback (most recent call last):
File "/run-1341144766-1067082874/solution.py", line 27, in
main()
File "/run-1341144766-1067082874/solution.py", line 11, in main
if len(s[i:j+1]) > 0:
MemoryError
Run Code Online (Sandbox Code Playgroud)
当我尝试运行以下程序时出现上述错误.有人可以解释什么是内存错误,以及如何解决这个问题?.程序将字符串作为输入并查找所有可能的子字符串并从中创建一个集合(按字典顺序排列),它应该在用户询问的相应索引处打印该值,否则应打印"无效"
def main():
no_str = int(raw_input())
sub_strings= []
for k in xrange(0,no_str):
s = raw_input()
a=len(s)
for i in xrange(0, a):
for j in xrange(0, a):
if j >= i:
if len(s[i:j+1]) > 0:
sub_strings.append(s[i:j+1])
sub_strings = list(set(sub_strings))
sub_strings.sort()
queries= int(raw_input())
resul = []
for i in xrange(0,queries):
resul.append(int(raw_input()))
for p in resul:
try:
print sub_strings[p-1]
except IndexError:
print 'INVALID'
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
mgo*_*ser 30
如果您遇到意外情况,MemoryError并且您认为应该有足够的RAM,那可能是因为您使用的是32位python安装.
如果您有64位操作系统,那么简单的解决方案是切换到64位的python安装.
问题是32位python只能访问~4GB的RAM.如果您的操作系统是32位,由于操作系统开销,这可能会进一步缩小.
您可以在此处了解有关32位操作系统限制为~4GB RAM的原因的更多信息:https://superuser.com/questions/372881/is-there-a-technical-reason-why-32-bit-windows-被限制到4GB-的夯
glg*_*lgl 21
这个在这里:
s = raw_input()
a=len(s)
for i in xrange(0, a):
for j in xrange(0, a):
if j >= i:
if len(s[i:j+1]) > 0:
sub_strings.append(s[i:j+1])
Run Code Online (Sandbox Code Playgroud)
对于大字符串而言,效率似乎非常低效且昂贵.
更好
for i in xrange(0, a):
for j in xrange(i, a): # ensures that j >= i, no test required
part = buffer(s, i, j+1-i) # don't duplicate data
if len(part) > 0:
sub_Strings.append(part)
Run Code Online (Sandbox Code Playgroud)
缓冲区对象保留对原始字符串以及start和length属性的引用.这样,就不会发生不必要的数据重复.
一串长度l具有l*l/2平均长度的子字符串l/2,因此内存消耗大致为l*l*l/4.使用缓冲区,它要小得多.
请注意,buffer()仅存在于2.x. 3.x有memoryview(),使用略有不同.
更好的方法是计算索引并根据需要删除子串.
一个内存错误意味着你的程序运行内存不足.这意味着您的程序以某种方式创建了太多对象.
在您的示例中,您必须查找可能消耗大量内存的算法部分.我怀疑你的程序被赋予非常长的字符串作为输入.因此,s[i:j+1]可能是罪魁祸首,因为它创建了一个新的列表.第一次使用它时,没有必要,因为您不使用创建的列表.您可以尝试查看以下内容是否有帮助:
if j + 1 < a:
sub_strings.append(s[i:j+1])
Run Code Online (Sandbox Code Playgroud)
要替换第二个列表创建,您应该使用glglgl建议的缓冲区对象.
另请注意,自您使用以来if j >= i:,您无需从xrange0 开始.您可以:
for i in xrange(0, a):
for j in xrange(i, a):
# No need for if j >= i
Run Code Online (Sandbox Code Playgroud)
更激进的替代方案是尝试重新编写算法,以便不预先计算所有可能的子字符串.相反,您可以简单地计算所询问的子字符串.