From 787715411522954660e9235c7eebe8eb896bc498 Mon Sep 17 00:00:00 2001 From: Timotej Lazar Date: Tue, 22 Sep 2015 15:51:10 +0200 Subject: Add Node.subtrees and Node.leaves functions --- monkey/graph.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'monkey') diff --git a/monkey/graph.py b/monkey/graph.py index c69d55c..7f02c60 100644 --- a/monkey/graph.py +++ b/monkey/graph.py @@ -19,6 +19,21 @@ class Node(object): nodes += n.preorder() return nodes + # Return a list of subtrees of [self]. + def subtrees(self): + yield self + for child in self.eout: + yield from child.subtrees() + + # Return the list of leaves' values (left-to-right). + def terminals(self): + if not self.eout: + return [self.data] + terminals = [] + for child in self.eout: + terminals.extend(child.terminals()) + return terminals + # Return a one-line string representation of [self]. def __str__(self): return '(' + str(self.data) + ' ' + \ -- cgit v1.2.1