Skip to content

Instantly share code, notes, and snippets.

@indera
Forked from aethanyc/construct_trees.py
Created January 10, 2017 20:28
Show Gist options
  • Save indera/aabd8e164341f896e85b243aa904a01b to your computer and use it in GitHub Desktop.
Save indera/aabd8e164341f896e85b243aa904a01b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This code resolves the problem described in
http://xahlee.info/perl-python/python_construct_tree_from_edge.html
"""
import collections
import json
def construct_trees(edges):
"""Given a list of edges [child, parent], return trees. """
trees = collections.defaultdict(dict)
for child, parent in edges:
trees[parent][child] = trees[child]
# Find roots
children, parents = zip(*edges)
roots = set(parents).difference(children)
return {root: trees[root] for root in roots}
if __name__ == '__main__':
edges = [[0, 2], [3, 0], [1, 4], [2, 4], [5, 6], [6, 7], [8, 6]]
print(json.dumps(construct_trees(edges), indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment