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!