[Tutor] tree or link-list questions.

Alan Gauld alan.gauld at yahoo.co.uk
Tue Jun 25 10:48:30 EDT 2019


On 25/06/2019 13:24, mhysnm1964 at gmail.com wrote:

A much less open ended question :-)

> class Node:
> 
>     def __init__(self, name, value):
>         self.parent = None
>         self.child = []


This should be plural if its a list. So call it children...
However I'm not really sure it should be a list, most
trees have two child nodes - called left and right by
convention. But some trees do have multiple children,
it's up to you.

>         self.name = name
>         self.value = value
> 
>     def add_child(self, name, value):
>         # Compare the new value with the parent node
>         if self.name:
>             if name != self.name:
>                 if  self.child is None:
>                     self.parent = self.child
>                     self.child = Node(name, value)
>                 else:
>                     self.child.add_child(name, value)
>         else:
>             self.name  = name
>             self.value = value
> 

My first comment would be that in OOP we should be trying to use
objects so rather than pass name,value into the method pass another
Node instance:

def add_child(self, newNode):
    if newNode.name != self.name
       self.children.append(newNode)
       newNode.parent = self

And if necessary call it like

myNode.add_child(Node(name, value))


However, looking at your code above you seem to be confused about which
node it adding which. self is the top level node to which you are adding
a child. So when finished you want the existing nodes parent to be
untouched and it's children list to include the new node.

Instead you are overwriting the list with the new Node instance and
setting the top level node's parent to the child. You really want the
child to have the top level as its parent.

The initial test of

if self.name

shouldn't be necessary since you assign name when you create the node.
Without a name the node is pointless so you should check if name is None
in the init method and throw an exception (ValueError?) if name is not
valid.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list