As a time-pass activity, I decided to implement a Tree(like) structure in python.
I implemented a Node
class (which alone serves the purpose here) like so:
class Node:
def __init__(self, name, parent, *data):
self.name = name
self.parent = parent
self.data = data
self.children = []
self.is_root = False
def __repr__(self):
return 'Node '+repr(self.name)
def dic(self):
retval = {self:[]}
for i in self.children:
retval[self].append(i.dic())
return retval
def display(self): # Here
pass
def has_children(self):
return bool(self.children)
def get_parent(self):
return self.parent
def add_child(self, name, *data):
child = Node(name, self,*data)
self.children.append(child)
return child
As you can see the display
function is not implemented.
Here's an example tree.
A = Node('A',Node)
A.is_root = True
B = A.add_child('B')
D = B.add_child('D')
C = A.add_child('C')
E = C.add_child('E')
F = C.add_child('F')
G = C.add_child('G')
Here's some sample output for display
.
>>> A.display()
A
+-^-+
B C
| +-+-+
D E F G
>>> C.display()
C
+-+-+
E F G
In the shortest form,
How can I "build" an ASCII tree (like above) from the Node class??
In a longer form,
The "Logic" of printing is:
- When there is only one child,
|
is put above the child. (D) - Else, Every child has a
+
above it, (B,C,E,F) - When there are even no. of children,
^
is put below the parent. (A) - Else, (there are odd no. of children)
+
is put below the parent. (C)
I have been thinking of starting from below. I realized that there has to be a call to the each of the children, but have been unable to implement anything (of that sorts or otherwise) that gave anything close to it.