0

So I just started learning Python so forgive me if I'm missing something here. I have a simple node class that has data and children as a list. In another class where Im recursively going through a grid, I attempt to add the entire grid to a node to create a sort of state space for the problem. My issue is that when I'm adding a child to its parent, it also adds itself as a child to itself for some reason.

This is my node class

class StateSpaceNode:
    def __init__(self, data=None, children=[]):
        self.data = data
        self.children = children

    def add_data(self, data):
        self.data = data

    def add_child(self, child):
        self.children.append(child)

and this is the portion where im adding the child

    def traverse_dfs(self, grid, x, y, seen, root):
        self.traverse_dfs_helper(grid, x, y, seen, root)

    def traverse_dfs_helper(self, grid, x, y, seen, old_root):
        key = "%s, %s" % (x, y)
        seen[key] = True

        if old_root.data is not None:
            node = StateSpaceNode()
            print("ADDING CHILD")
            print("NEW NODE:", node)
            print("NEW NODE CHILDREN: ", node.children)
            node.add_data(copy.deepcopy(grid))
            old_root.add_child(node)
            print("PARENT CHILDREN:", old_root.children)
            print("CHILDREN TO NEW NODE:", node.children)
        else:
            print("MAKING ROOT")
            old_root.add_data(copy.deepcopy(grid))
            print("OLD ROOT DATA ADDED", old_root.data)
            node = old_root
            print("CHILDREN TO OLD ROOT", node.children)

Take note of the print statements. This is the output for that portion of the code.

MAKING ROOT
OLD ROOT DATA ADDED [[0, 0], [0, 2]]
CHILDREN TO OLD ROOT []
ADDING CHILD
NEW NODE: <state_space.StateSpaceNode object at 0x104d2dcc0>
NEW NODE CHILDREN:  []
PARENT CHILDREN: [<state_space.StateSpaceNode object at 0x104d2dcc0>]
CHILDREN TO NEW NODE: [<state_space.StateSpaceNode object at 0x104d2dcc0>]

and if I print the tree out, it just keeps going on and on with the same child. However, the "ADDING CHILD" portion only happens three times in total so Im not sure whats going on. Any help is appreciated!

dannyyy
  • 149
  • 2
  • 8
  • `def __init__(self, data=None, children=[]): self.data = None self.children = []` , why adding two times – sahasrara62 Jul 10 '19 at 06:17
  • I mean, thats just in case I initialize the code in one line in other sections. I don't do it here for clarity's sake – dannyyy Jul 10 '19 at 06:20
  • 1
    Possible duplicate of ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – Stop harming Monica Jul 10 '19 at 06:29

0 Answers0