Hello All,

 

I am back!!! I forget which movie that comes from. 

 

Anyway, my issue is I am getting the same node being added to the parent node 
of my tree below. I have traced the code and do not understand why. This occurs 
when the loop which calls the addNode function has only looped once. I have had 
the return statement present and commented out with the same result. The length 
of the children list is 2 when it should be 1. 

 

AddNode is using recursive functionality. I suspect the function should be in 
the object itself, but I have it outside for now to work out my logic. I am 
sure there is a logic issue here in the area of OOPS, but I cannot see it. 

 

The aim is two only ever have one word in the children list regardless how many 
times it appears in the original source. Thus if the string has “the brown fox” 
and “the brown car”.  The following has to occur:

*       Children list in the root node will only have the “the” node once.
*       Children list in the “the”  node will only have the “brown” node once.
*       Children in the “brown”  node will have two nodes ‘cow’ and ‘car’.

 

Below is the code:

 

def addNode(words, tree):

    # creates the branch of words for the tree

    if words:

        wordExists = False 

        for child in tree.children:

            if words[0] == child.name:

                wordExists = True

            # end if

        # end for

        if not wordExists:

            tree = tree.add(words[0], 0)

        addNode(words[1:], tree)

    # end if

# note, the below has been uncommented with the same issue.

    #return tree 

 

class Node(object):

# I am not 100% sure the purpose of (object) does.

    def __init__(self, name, value):

        self.parent = None

        self.children = []

        self.name = name

        self.value = value

    def add(self, name, value):

        node1=Node(name, value)

        self.children.append(node1)

        node1.parent=self

        return node1

 

…. Bunch a code to load the files.

 

for account_no, date, line, amount in records:

    tree.children.append(addNode(line.split(), tree))

 

 

 

note: I have tried Allan’s suggestion as shown below and could not get it to 
work. I am currently reading his book on object programming to learn more about 
OOPS. This is how I worked out the recursive function. 😊

 

def add_child(self, newNode):

    if newNode.name != self.name

       self.children.append(newNode)

       newNode.parent = self

 

myNode.add_child(Node(name, value))

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to