I was looking for a possible implementation of tree printing, which prints the tree in a user-friendly way, and not as an instance of object.
I came across this solution on the net:
source: http://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html
class node(object):
def __init__(self, value, children = []):
self.value = value
self.children = children
def __repr__(self, level=0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.__repr__(level+1)
return ret
This code prints the tree in the following way:
'grandmother'
'daughter'
'granddaughter'
'grandson'
'son'
'granddaughter'
'grandson'
Is it possible to have the same result but without changing the __repr__
method, because I am using it for another purpose.
EDIT:
Solution without modifying __repr__
and __str__
def other_name(self, level=0):
print '\t' * level + repr(self.value)
for child in self.children:
child.other_name(level+1)
Why don't you store it as a treelib object and print it out similar to how we print the CHAID tree out here with more relevant node descriptions related to your use case?
Yes, move the
__repr__
code to__str__
, then callstr()
on your tree or pass it to theprint
statement. Remember to use__str__
in the recursive calls too:Demo: