Created
December 18, 2009 21:38
-
-
Save cdent/259779 to your computer and use it in GitHub Desktop.
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
from pprint import pprint | |
foo = {'name': 'foo'} | |
bar = {'name': 'bar'} | |
baz = {'name': 'baz'} | |
mytopic = {'name': 'mytopic'} | |
myothertopic = {'name': 'myothertopic'} | |
can = {'name': 'can'} | |
foo['parent'] = mytopic | |
bar['parent'] = foo | |
baz['parent'] = mytopic | |
can['parent'] = myothertopic | |
things = [foo, myothertopic, bar, can, baz, mytopic] | |
tops = [] | |
while things: | |
this = things.pop() | |
try: | |
parent = this['parent'] | |
except KeyError: | |
tops.append(this) | |
continue | |
try: | |
parent['child'].append(this) | |
except KeyError: | |
parent['child'] = [this] | |
pprint(tops) | |
print "####### now traverse" | |
def traverse(node): | |
try: | |
children = node['child'] | |
print 'node ', node['name'] | |
print 'kids:' | |
for child in children: | |
print '\t', child['name'] | |
traverse(child) | |
except KeyError: | |
return | |
for top in tops: | |
print 'top:', top['name'] | |
traverse(top) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment