Last active
August 29, 2015 14:04
-
-
Save imran31415/afc820534a654dad0e80 to your computer and use it in GitHub Desktop.
orchard
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
''' | |
trivial orchard example | |
exploring multidimensional dynamic data types | |
''' | |
def create_orchard(): | |
return {'orchard':[]} | |
def add_tree_row(orchard, n=1): | |
for x in xrange(n): | |
orchard['orchard'].append({'tree_row':[]}) | |
return orchard | |
def add_tree(orchard, tree_row_index, n=1 ): | |
for x in xrange(n): | |
orchard['orchard'][tree_row_index]['tree_row'].append({'tree':[]}) | |
return orchard | |
def add_apple(orchard, tree_row_index, tree_index, n=1): | |
for x in xrange(n): | |
orchard['orchard'][tree_row_index]['tree_row'][tree_index]['tree'].append('apple') | |
return orchard | |
# this function is just used to indent and print the nested elements of a given dynamic datatype | |
# modified from stack overflow to support lists | |
def pretty(d, indent=0): | |
if isinstance(d, dict): | |
for key, value in d.iteritems(): | |
print '-\t' * indent + str(key) | |
if isinstance(value, dict): | |
pretty(value, indent+1) | |
elif isinstance(value, list): | |
for i in value: | |
pretty(i, indent+1) | |
else: | |
print '-\t' * (indent+1) + str(value) | |
else: | |
print '-\t' * (indent+1) + d | |
#creating the orchard | |
o = create_orchard() | |
o = add_tree_row(o) | |
#add tree to first tree_row | |
o = add_tree(o, 0) | |
#add apple to first tree in first tree_row | |
o = add_apple(o, 0 , 0) | |
print '_____________________________________________' | |
print '*An orchard with 1 tree row, 1 tree, 1 apple\n' | |
pretty(o,1) | |
#add apple to first tree in first tree_row | |
o = add_apple(o,0,0) | |
#add tree to first tree_row | |
o = add_tree(o,0) | |
#add second tree_row to orchard | |
o = add_tree_row(o) | |
# add tree to second tree_row | |
o = add_tree(o,1) | |
print '_____________________________________________' | |
print '*after adding a few elements' | |
pretty(o,1) | |
# add 10 apples to first tree in second tree_Row | |
o = add_apple(o,1,0,10) | |
# add 5 trees to second tree_row | |
o = add_tree(o,1,5) | |
print '_____________________________________________' | |
print '*After adding a bunch of stuff\n' | |
pretty(o,1) | |
print '_____________________________________________' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment