Skip to content

Instantly share code, notes, and snippets.

@evz
Created February 9, 2016 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evz/04973de308642bd1108d to your computer and use it in GitHub Desktop.
Save evz/04973de308642bd1108d to your computer and use it in GitHub Desktop.
Edgelist to Tree
if __name__ == "__main__":
import pprint
import copy
engine = init_engine(DB_CONN)
children = [(1,2),(1,3),(2,4)]
edgelist = engine.execute(children)
tree = {}
seen_nodes = set()
def addLeaf(tree, parent, child):
signal = False
if parent in tree:
tree[parent].update({child: {}})
signal = tree
elif tree:
for branch in tree.values():
if addLeaf(branch, parent, child):
signal = True
else:
signal = False
return signal
for parent, child in edgelist:
if child in seen_nodes:
tree[parent].update({child: copy.deepcopy(tree[child])})
del tree[child]
else:
result = addLeaf(tree, parent, child)
if not result:
tree[parent] = {child: {}}
seen_nodes.update([parent, child])
pprint.pprint(tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment