python recursive iteration exceeding limit for tree implementation

Posted by user3698027 on Stack Overflow See other posts from Stack Overflow or by user3698027
Published on 2014-06-02T03:21:11Z Indexed on 2014/06/02 3:25 UTC
Read the original article Hit count: 190

Filed under:
|
|
|

I'm implementing a tree dynamically in python. I have defined a class like this...

class nodeobject():

    def __init__(self,presentnode=None,parent=None):
        self.currentNode = presentnode
        self.parentNode = parent
        self.childs = []

I have a function which gets possible childs for every node from a pool def findchildren(node, childs): # No need to write the whole function on how it gets childs

Now I have a recursive function that starts with the head node (no parent) and moves down the chain recursively for every node (base case being the last node having no children)

def tree(dad,children):

    for child in children:
        childobject = nodeobject(child,dad)
        dad.childs.append(childobject)
        newchilds = findchildren(child, children)
        if len(newchilds) == 0:
            lastchild = nodeobject(newchilds,childobject)
            childobject.childs.append(lastchild)
            loopchild = copy.deepcopy(lastchild)
            while loopchild.parentNode != None:
                print "last child"
        else:
            tree(childobject,newchilds)

The tree formation works for certain number of inputs only. Once the pool gets bigger, it results into "MAXIMUM RECURSION DEPTH EXCEEDED"

I have tried setting the recursion limit with set.recursionlimit() and it doesn't work. THe program crashes. I want to implement a stack for recursion, can someone please help, I have gone no where even after trying for a long time ?? Also, is there any other way to fix this other than stack ?

© Stack Overflow or respective owner

Related posts about python

Related posts about recursion