Created
June 13, 2016 17:10
-
-
Save quatrix/46cb8970de2948eda1c69fa8bad32cfc 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): | |
while True: | |
changed = False | |
for k, v in n.iteritems(): | |
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 | |
for p in url.split('/'): | |
if p not in r: | |
r[p] = {} | |
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