-
-
Save vbmendes/2014896 to your computer and use it in GitHub Desktop.
test_hash.py
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
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
import json | |
cars = json.loads(open('./fixtures/fipe_carro.json').read()) | |
tree = {} | |
for v in cars: | |
for name in v['translated_names']: | |
for i in xrange(1, len(name) + 1): | |
tree_node = tree.get(name[:i], []) | |
tree_node.append(v) | |
tree[name[:i]] = tree_node |
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 | |
class Tree(dict): | |
def push(self, obj): | |
""" | |
Pushes a new object in the tree. | |
""" | |
for name in obj['translated_names']: | |
for i in xrange(1, len(name) + 1): | |
tree_node = self.setdefault(name[:i], []) | |
tree_node.append(obj) | |
@classmethod | |
def from_list(cls, list_): | |
""" | |
Build tree form a list of objects. | |
""" | |
tree = cls() | |
for obj in list_: | |
cls.push(obj) | |
return tree | |
cities = json.loads(open('./fixtures/cities.json').read()) | |
tree = Tree.from_list(cities) | |
natal = tree['natal'] |
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
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
from api.nary import Tree | |
import json | |
cars = json.loads(open('./fixtures/fipe_carro.json').read()) | |
tree = Tree.from_list(cars, lambda vehicle: vehicle['translated_names']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Curti muito a ideia de organizar a construção da árvore dentro de uma classe que herda de dict. Fica mais limpo! :)