diff options
author | Timotej Lazar <timotej.lazar@araneo.org> | 2015-09-22 15:51:10 +0200 |
---|---|---|
committer | Timotej Lazar <timotej.lazar@araneo.org> | 2015-09-22 15:51:10 +0200 |
commit | 787715411522954660e9235c7eebe8eb896bc498 (patch) | |
tree | f4ea76a0e766e12298d4641fc111aaad555220b8 | |
parent | 2c61fec2140da5ec9a5aee8a7d6d3f0f2d3b0897 (diff) |
Add Node.subtrees and Node.leaves functions
-rw-r--r-- | monkey/graph.py | 15 |
1 files changed, 15 insertions, 0 deletions
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) + ' ' + \ |