Skip to content

Instantly share code, notes, and snippets.

@matthandlersux
Forked from hrldcpr/tree.md
Created March 10, 2012 18:39
Show Gist options
  • Save matthandlersux/2012439 to your computer and use it in GitHub Desktop.
Save matthandlersux/2012439 to your computer and use it in GitHub Desktop.
one-line tree datastructure in python

in python:

from pprint import pprint
from collections import defaultdict


# one-line definition of a tree:
def tree(): return defaultdict(tree)

taxonomy = tree()
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Felis']['cat']
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Panthera']['lion']
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['dog']
taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['coyote']
taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['tomato']
taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['potato']
taxonomy['Plantae']['Solanales']['Convolvulaceae']['Ipomoea']['sweet potato']


def dicts(t): return {k: dicts(v) for k,v in t.iteritems()}
def print_tree(t): pprint(dicts(t))

print_tree(taxonomy)
# {'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Canidae': {'Canis': {'coyote': {},
#                                                                             'dog': {}}},
#                                                       'Felidae': {'Felis': {'cat': {}},
#                                                                   'Panthera': {'lion': {}}}}}}},
#  'Plantae': {'Solanales': {'Convolvulaceae': {'Ipomoea': {'sweet potato': {}}},
#                            'Solanaceae': {'Solanum': {'potato': {},
#                                                       'tomato': {}}}}}}

in ruby:

class Tree < Hash
	def initialize
		super{|hash, key| hash[key] = Tree.new }
	end
end

taxonomy = Tree.new
taxonomy[:Animalia][:Chordata][:Mammalia][:Carnivora][:Felidae][:Felis][:cat]
taxonomy[:Animalia][:Chordata][:Mammalia][:Carnivora][:Felidae][:Panthera][:lion]
taxonomy[:Animalia][:Chordata][:Mammalia][:Carnivora][:Canidae][:Canis][:dog]
taxonomy[:Animalia][:Chordata][:Mammalia][:Carnivora][:Canidae][:Canis][:coyote]
taxonomy[:Plantae][:Solanales][:Solanaceae][:Solanum][:tomato]
taxonomy[:Plantae][:Solanales][:Solanaceae][:Solanum][:potato]
taxonomy[:Plantae][:Solanales][:Convolvulaceae][:Ipomoea][:sweet_potato]

require "pp"
pp taxonomy.inspect
# {:animalia=>
#   {:chordata=>
#     {:mammalia=>
#       {:carnivora=>
#         {:felidae=>{:felis=>{:cat=>{}}, :panthera=>{:lion=>{}}},
#          :canidae=>{:canis=>{:dog=>{}, :coyote=>{}}}}}}},
#  :plantae=>
#   {:solanales=>
#     {:solanaceae=>{:solanum=>{:tomato=>{}, :potato=>{}}},
#      :convolvulaceae=>{:ipomoea=>{:sweet_potato=>{}}}}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment