Skip to content

Instantly share code, notes, and snippets.

@vbmendes
Forked from rafaelcaricio/.gitignore
Created March 11, 2012 03:38
Show Gist options
  • Save vbmendes/2014896 to your computer and use it in GitHub Desktop.
Save vbmendes/2014896 to your computer and use it in GitHub Desktop.
test_hash.py
#!/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
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']
#!/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'])
@rafaelcaricio
Copy link

Curti muito a ideia de organizar a construção da árvore dentro de uma classe que herda de dict. Fica mais limpo! :)

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