It would be easier to do e.g.
1 Life
1.1 Bacteria
1.2 Eukaryota
1.2.1 plants
1.2.2 animals
1.2.2.1 Vertebrates
1.2.2.1.1 amphibians
1.2.2.1.2 reptiles
1.2.2.1.3 mammals
As then you don't have to check explicitly whether the node has children to print
it out. A couple of useful bits of code:
for index, child in enumerate(obj.children, 1):
This will number each of the children
, using one-based indices.
''.join(('\t', indent, '.', str(index)))
Adds a new tab to the start of the previous indent
, and the index
to the end. Putting that together:
def print_hierarchy(root, indent="1"):
print('\t'.join([indent, root.name]))
for index, child in enumerate(root.children, 1):
print_hierarchy(child, ''.join(('\t', indent, '.', str(index))))
I get:
1 life
1.1 bacteria
1.2 eukaryota
1.2.1 plants
1.2.2 animals
1.2.2.1 vertebrates
1.2.2.1.1 amphibians
1.2.2.1.2 reptiles
1.2.2.1.3 mammals
For fuller functionality, it gets more complex:
def print_hierarchy(root, indent=None, dec=None, zeroes=False):
if indent is None:
indent = []
elif isinstance(indent, str):
indent = [indent]
if dec is None:
dec = []
zeroes = False
elif isinstance(dec, int):
dec = [str(dec)]
elif isinstance(dec, str):
dec = [dec]
print(' '.join([''.join(indent),
'.'.join(dec + ["0"] if root.children and zeroes else dec),
root.name]))
for index, child in enumerate(root.children, 1):
print_hierarchy(child,
indent + [indent[0]] if indent else indent,
dec + [str(index)] if dec else dec,
zeroes)
print_hierarchy(root, "\t", 1, True)