Skip to content

Instantly share code, notes, and snippets.

@quatrix
Created June 13, 2016 17:41
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 quatrix/47c026785d67c9d29896d2b7885d715d to your computer and use it in GitHub Desktop.
Save quatrix/47c026785d67c9d29896d2b7885d715d to your computer and use it in GitHub Desktop.
import json
def flatten(n):
if isinstance(n, bool):
return
while True:
changed = False
for k, v in n.iteritems():
if isinstance(v, bool):
continue
if len(v.keys()) == 1:
del n[k]
vk = v.keys()[0]
n[k + '/' + vk] = v[vk]
changed = True
else:
flatten(v)
if not changed:
break
return n
class Tree(object):
def __init__(self):
self.root = {}
def add(self, url):
r = self.root
url = url.split('/')
for i, p in enumerate(url):
if p not in r:
r[p] = {}
if (i == len(url) - 1):
r[p][''] = True
r = r[p]
if __name__ == '__main__':
urls = [
'blog/a/a/a',
'blog/a/a/b',
'blog/a/b/a',
'blog/a/c/a',
'blog/a/d',
'blog/a/d/e',
]
t = Tree()
map(t.add, urls)
print(json.dumps(flatten(t.root), indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment