I have this exercise:
You have a tree graph as input, and you need to remove its leaves. So you need to remove the empty lists from a list of lists.
For example
The solution:
def tree_cut(tree):
return [tree_cut(x) for x in tree if x]
uses a list comprehension to iterate, filter and transform nodes in the tree.
Can be written also in terms of map() and filter():
def tree_cut(tree):
return list(map(tree_cut, filter(None, tree)))
The if x
part tests if the list is not empty.
>>> tree = [[[[], []], [[], []]], [[], [], []]]
>>> tree_cut(tree)
[[[], []], []]