Dhiraj Thakur
Dhiraj Thakur

Reputation: 726

string[i:length] giving memory error

def suffix(stng):
    list = []
    length = len(stng)
    for i in range(length):
         x = stng[i:length]   ## This gives a Memory Error..See below
         list.append(x)
    return list

This piece of code is a part of my solution of a problem on interviewstreet.com but when i submit it i get a Memory error...i want to know how to correct it?

This is the traceback:

Original exception was:
Traceback (most recent call last):
File "/run-1342184337-542152202/solution.py", line 35, in
listofsuffix=suffix(var)
File "/run-1342184337-542152202/solution.py", line 13, in suffix
x=stng[i:length]
MemoryError

Upvotes: 0

Views: 2739

Answers (2)

mgilson
mgilson

Reputation: 310089

"I need to return a list" -- This is highly unlikely. You just need to return an object which looks enough like a list to make it work.

class FakeList(object):
    def __init__(self,strng):
        self.string=strng
        self._idx=0
    def __getitem__(self,i):
        return self.strng[:i]
    def __len__(self):
        return len(self.string)
    def __iter__(self):
        return self
    def __contains__(self,other):
        return other in self.string
    def next(self):
        if(self._idx<len(self)):
           self._idx+=1
           return self[self._idx-1]
        else:
           raise StopIteration


a=FakeList("My String")
print a[3]
print a[4]
for i in a:
    print i

This creates an object which you can access randomly and iterate over like a list. It also will allow you to call len(my_fake_list). It doesn't support slicing, and a myriad of other methods pop, append, extend ... Which of those you need to add depends on which ones you use.

Upvotes: 0

Ned Batchelder
Ned Batchelder

Reputation: 375834

A MemoryError means you have consumed all your RAM. You are creating a list containing all trailing parts of an original string. If your original string is too long, you will consume a lot of memory.

One possibility is to use a generator to produce the suffixes one at a time instead of creating a list of all of them:

def suffixes(stng):
    for i in xrange(len(stng)):
         yield stng[i:]

If the caller of suffixes simply iterates over the result, you don't even have to change the caller. If you truly needed an explicit list, then you'll need a different solution.

Upvotes: 10

Related Questions