Home > front end >  Tree data structure __str__ method
Tree data structure __str__ method

Time:11-05

class TreeNode:
    def __init__(self,data,children = []):
        self.data = data
        self.children = children


    def __str__(self,level=0):
        ret = " " * level   str(self.data)   '\n'
        for child in self.children:
           ret  = child.__str__(level 1)

        return ret

    # adding the children to the tree node
    def addchildren(self,TreeNode):
        self.children.append(TreeNode)

Ques1 : Please explain def __str__(self,level=0):. Especially child.__str__(level 1)

drinks = TreeNode('Drinks',[])
cold = TreeNode('Cold',[])
hot = TreeNode('Hot',[])
cola = TreeNode('Cola',[])
cappucino = TreeNode('Cappucino',[])
drinks.addchildren(cold)
drinks.addchildren(hot)
cold.addchildren(cola)
hot.addchildren(cappucino)

print(drinks)

Ques 2: And one more thing why is it giving this type error(given below) if I use self.children.append(TreeNode.data), I know it's not gonna work but why the print( ) statement is throwing this error but not in self.children.append(TreeNode). Why is it saying expected 0 arguments, got 1 ?

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_944/4195955341.py in <module>
----> 1 print(drinks)

~\AppData\Local\Temp/ipykernel_944/3676504849.py in __str__(self, level)
      8         ret = " " * level   str(self.data)   '\n'
      9         for child in self.children:
---> 10             ret  = child.__str__(level 1)
     11 
     12         return ret

TypeError: expected 0 arguments, got 1

CodePudding user response:

def __str__(self,level=0):
    ret = " " * level   str(self.data)   '\n'
    for child in self.children:
       ret  = child.__str__(level 1)

    return ret

" " * level means repeat space level times. Default value for level is 0 for object itself and level plus one for children, these children again call __str__ of theirs children with level increased by one. So current object has 0 spaces at start of its line, its' children 1 space at start of their lines, childrens of children 2 spaces at start of their lines and so on, which provides nice visual representation akin to what you might encounter when browsing catalogs e.g.:

rootdir
 dir1
  dir11
  dir12
 dir2
  dir21
  dir22

where dir11 and dir12 are inside dir1, dir21 and dir22 are inside dir2, dir1 and dir2 are inside rootdir.

It is uncommon for python __str__ methods to have more than 1 argument (any argument beyond self). Say one of child is tuple (1,2,3) then when you try to print your tree, it does try to print that with level equal to 1, that is

(1,2,3).__str__(1)
  • Related