Skip to content

Instantly share code, notes, and snippets.

@shivamMg
Created August 31, 2017 21:53
Show Gist options
  • Select an option

  • Save shivamMg/2980413c41a8d84a99c29ca79d75a78e to your computer and use it in GitHub Desktop.

Select an option

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)
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))
@shivamMg

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment