Created
June 13, 2016 17:41
-
-
Save quatrix/47c026785d67c9d29896d2b7885d715d to your computer and use it in GitHub Desktop.
This file contains 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 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