Newbie here, I am struggling with a homework question. We are supposed to write a function that prints out a "tree". This tree contains labels, branches and trees. A tree is constructed in the following way:
example_tree = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
The tree-function is already defined. It creates a label and can optionally contain a new sublist (the "branches").
Now we are given the following task:
"""Print a representation of this tree in which each node is
indented by two spaces times its depth from the root.
>>> print_tree(tree(1))
1
>>> print_tree(tree(1, [tree(2)]))
1
2
>>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
>>> print_tree(numbers)
1
2
3
4
5
6
7
"""
Our first intuition was to build the following function:
def print_tree(t, indent=0):
for i in t:
if len(t) > 1:
print(i)
indent = indent 1
else:
print(i)
This results in the following:
1
[2]
[3, [4], [5]]
[6, [7]]
Might someone give a pointer on how we arrive at the correct result? How to work with the indent for example? The coding is done on Google Colab.
Thanks a lot!
CodePudding user response:
This sort of task (processing tree-like structure) is most commonly done by using recursion - each branch is essentialy a tree on its own, so you treat it in the same way.
class Tree:
def __init__(self, label, branches = None):
if not branches:
branches = []
self.label = label
self.branches = branches
def printTree(self, depth = 0):
print(" " * depth str(self.label))
for branch in self.branches:
branch.printTree(depth 1)
numbers = Tree(1, [Tree(2), Tree(3, [Tree(4), Tree(5)]), Tree(6, [Tree(7)])])
numbers.printTree()
Output:
1
2
3
4
5
6
7