Home > Enterprise >  maximum recursion depth exceeded while calling a Python object in n ary tree [duplicate]
maximum recursion depth exceeded while calling a Python object in n ary tree [duplicate]

Time:09-17

I'm trying to implement a solution for following:

interface Monarchy {
  void birth(String child, String parent);
  List<String> getOrderOfSuccession();
}
             king
          /         \
       a1            a2
      /  \          /  \
    b1   b2       c1    c2
   / \     \
d1    d2    d3
Order of Succession: king -> a1 -> b1 -> d1 -> d2 -> b2 -> d3 -> a2 -> c1 -> c2

This is my solution:

class Person:
    name = ""
    children = []
    is_alive = True

    def __init__(self, name):
        self.name = name


class MonarchyNew:
    head = None
    members = dict()

    def __init__(self, name):
        p = Person(name)
        self.head = p
        self.members[name] = p

    def birth(self, child_name: str, born_to: str) -> 'MonarchyNew':
        parent = self.members[born_to]
        child_node = Person(child_name)
        parent.children  = [child_node]
        self.members[child_name] = child_node

        return self


    def __dfs_core(self, head: Person, succession: List[str]):
        if head.is_alive:
            succession.append(head.name)
        for c in head.children:
            self.__dfs_core(c, succession)

    def get_order_of_succession(self) -> List[str]:
        succession = []
        self.__dfs_core(self.head, succession)
        return succession

But it is creating infinite childs when I'm trying to run it like this:

m = MonarchyNew("Jake")
m.birth("Catherine", "Jake")
print(m.get_order_of_succession())

Error that I'm getting: maximum recursion depth exceeded while calling a Python object

I've found out, this is happening when doing parent.children = [child_node]. child_node is getting added in children array of the child [ie: 'Catherine' is getting added as children to 'Catherine'] recursively, creating a infinite loop.

Resulting in: Jake -> Catherine -> Catherine -> Catherine -> Catherine X [infinite]

I'm nnot able to figure out why is this happening. Can someone please help?

CodePudding user response:

You have defined children as a static variable of Person, i.e. there is only one list that is shared by all instances of Person. That is not what you want. So define children as an instance attribute in the constructor:

    def __init__(self, name):
        self.name = name
        self.children = []
  • Related