Memory error in recursive function (Python 2.7.3) -


i'm running memory error in 1 of recursive function.

def allpaths(self, adjmat, start, stop, flag=[0], walks=[]):     walks = walks + [start]     if start == stop:         return [walks]     loc = 0     flag=flag*len(adjmat)     output = []     value in adjmat[start]:         if value > 0.0:             if flag[loc] < 3:                 flag[loc]+=1                 paths = self.allpaths(adjmat, loc, stop, flag, walks)                 k in paths:                     output.append(k)         loc += 1     return output 

one example input fine memory error different matrix.

>>>print test.allpaths([[0.0, 0.9, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0],           [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],           [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],           [0.0, 0.0, 0.0, 0.8, .15, .05, 0.0, 0.0],           [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],           [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],           [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],           [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]],0,7) [[0, 1, 2, 3, 3, 3, 4, 7], [0, 1, 2, 3, 3, 3, 5, 7], [0, 1, 2, 3, 3, 4, 7], [0, 1, 2, 3, 3, 5, 7], [0, 1, 2, 3, 4, 7], [0, 1, 2, 3, 5, 7], [0, 6, 7]]  >>>print test.allpaths([[0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],           [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],           [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],           [0.8, 0.0, 0.0, 0.0, .05, .15, 0.0, 0.0],           [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],           [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],           [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],           [0.9, 0.0, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0]],0,7) 

the error seems occur @ line "flag=flag*len(adjmat)". suggestions?

each recursive call increases size of flag list factor of len(adjmat).

the first call function uses flag list len(adjmat) elements , passes recursive call. there list multiplied len(adjmat), resulting in len(adjmat) * len(adjmat) elements. few recursive calls can out of hand , run out of memory store excessively large flag list.


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -