Created
January 13, 2014 04:26
-
-
Save zpconn/8394706 to your computer and use it in GitHub Desktop.
Given a list of pairs, each containing the name of a node and the name of its parent, respectively, this builds the full tree as a nested dictionary. Note that the parent of the root node is specified by None.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def build(pairs, root=None): | |
tree = {} | |
for (child, parent) in pairs: | |
if parent == root: | |
tree[child] = build(filter(lambda x: x != (child, parent), pairs), child) | |
return tree | |
print build([("H", "G"), ("F", "G"), ("G", "D"), ("E", "D"), ("A", "E"), ("B", "C"), ("C", "E"), ("D", None)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment