I need to write a function in Python that takes a tree and an index and returns the subtree or leaf at that index.
I tried with loops and nested loops until I realized that the tree that had to run the tests was always the same:
JavaScript
x
2
1
tree = (((1, 2), 3), (4, (5, 6)), 7, (8, 9, 10))
2
which actually looks like this:
So all I needed to pass the tests given was this:
JavaScript
1
10
10
1
def tree_ref(tree, index):
2
if len(index) == 1:
3
print tree[index[0]]
4
elif len(index) == 2:
5
print tree[index[0]][index[1]]
6
elif len(index) == 3:
7
print tree[index[0]][index[1]][index[2]]
8
else:
9
return False
10
For example, for an index = (1, 1, 0) it should return the number 5 and it does.
However, I know this code won’t work for other trees or index with more than 3 elements. How could I make it work for any given tree and index?
Advertisement
Answer
You should try to use recursion.
Something like below:
JavaScript
1
6
1
def tree_ref(tree, index):
2
if len(index) == 1:
3
print tree[index[0]]
4
else:
5
tree_ref(tree[index[0]], index[1:])
6