Last active
November 30, 2022 08:03
-
-
Save aethanyc/8313640 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/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
because the variable "trees "is a default dict , which will automatically construct an object(a empty dict in this case) when key does not exist, so when you access trees[parent], a new dict indicating that parent node will be built if it is not exist at the moment.