def _delete_nonterminal_leaves(edges, terminals): r"""Prunes all non-terminal leaves from the tree. Given the edges of a tree and a set of terminal vertices, this method removes all non-terminal leaves and returns the new tree edges. Parameters ---------- edges : list A list of the edges of the tree. terminals : set A set of the terminal vertices. Returns ------- tree_edges : list A list of the edges of the pruned tree. Notes ----- This method deletes all non-terminal leaves from the tree. This process is repeated until all leaves are terminals. There is room to improve this algorithm. """ # Form a graph from the edge list. tree = Graph() for (u, v) in edges: tree.add_edge(u, v) # Now delete all leaves that are not terminals while True: leaves = tree.leaves() changed = False for leaf in leaves: if leaf not in terminals: tree.delete_vertex(leaf) changed = True if not changed: break return tree.edges()