Python - how to make tree without any library

43 Views Asked by At

I need to make a **tree **with arrows and indent in python. I cannot use any libraries.

It should work like this: 
INPUT:
[[[1, [True, ['abc', 'def']]], [2, [3.14159, 6.023e23]]], 42]

PARAMS:
    indent = 4
    separator = '.'

OUTPUT:
42
├──>1
│...└──>True
│.......├──>abc
│.......└──>def
└──>2
....├──>3.14159
....└──>6.023e+23



[6, [[[[1, [2, 3]], [42, [-43, 44]]], 4], 5]]

PARAMS:
    indent = 2
    separator = ' '

OUTPUT:
6
└>5
  └>4
    ├>1
    │ ├>2
    │ └>3
    └>42
      ├>-43
      └>44

I now have this code, it does not connect the lines. I need to know the lenght of child and connect them.

# Description: Function to print a tree structure
def render_tree(tree: list = None, indent: int = 2, separator: str = ' ') -> str:
    
    #exception handling
    if tree is None or not isinstance(tree, list) or indent <= 1 or len(tree) < 2:
        raise Exception('Invalid tree')
    
    def printnode (depth, parent):
        for inx, child in enumerate (parent): 
            
            #print first element
            if (depth == 0 and type(child) != list):
                print(f"{child}")
                
            #print the rest of the elements
            elif (type(child) != list): 
                if inx == len(parent) - 1:
                    print(f"{separator * (depth -1)}└>{child}")      #Depth * indent  addd       
                else:
                    print(f"{separator * (depth -1)}├>{child}")         
        
        #loop to print the nested lists
        for child in parent:
            if (type(child) == list ): 
                printnode(depth+1, child )

    #initial call      
    printnode(0, tree)
    return ''

input data mostly:

tree1 =[[[1, [True, ['abc', 'def']]], [2, [3.14159, 6.023e23]]], 42]
tree2 =[[[1, [[True, ['abc', 'def']], [False, [1, 2]]]], [2, [3.14159, 6.023e23, 2.718281828]], [3, ['x', 'y']], [4, []]], 42]
tree3 =[6, [[[[1, [2, 3]], [42, [-43, 44]]], 4], 5]]
tree4 =[6, [5, ['dva\nradky']]]

I tried making a variable for parent lenght, but didn't get anything from that approach.

0

There are 0 best solutions below