Created
August 31, 2017 21:53
-
-
Save shivamMg/2980413c41a8d84a99c29ca79d75a78e to your computer and use it in GitHub Desktop.
Given a list of prefixes create a tree structure. (sort of how objects are stored in AWS S3. Another example could be Consul)
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
| import json | |
| def attach_branch(tree, branch): | |
| l = len(branch) | |
| node = branch[0] | |
| # If node doesn't exist get an empty subtree | |
| subtree = tree.get(node, {}) | |
| if l == 1: | |
| # Create leaf node | |
| tree.update({node: subtree}) | |
| return tree | |
| subtree.update(attach_branch(subtree, branch[1:])) | |
| tree.update({node: subtree}) | |
| return tree | |
| if __name__ == '__main__': | |
| root_list = [] | |
| tree = {} | |
| prefixes = [ | |
| 'F', | |
| 'A|B|C', | |
| 'A|B|D', | |
| 'B|C|D', | |
| 'B|C|E', | |
| 'A', | |
| ] | |
| for branch in map(lambda x: x.split('|'), prefixes): | |
| if len(branch) == 1: | |
| root_list.append(branch[0]) | |
| continue | |
| tree = attach_branch(tree, branch) | |
| root_list.append(tree) | |
| print(json.dumps(root_list, indent=2)) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://ideone.com/ky5pDh