[Tutor] treeTraversal, nested return?

jjcrump at uw.edu jjcrump at uw.edu
Fri Jun 4 19:15:26 CEST 2010


any observations might be helpful. For the display of database contents I 
have the following problem:

Database querys will return data to me in tuples of the following sort:
each tuple has a unique id, a parent id, and a type.

a parent id of 0 indicates that the element has no parent.
not all data elements have children
image elements have no children and must have a parent

So the contents of the db is a tree of sorts:

(1, 0, work)
(555, 1, image)
(556, 1, work)
(557, 556, image)
(558, 556, work)
(559, 558, image)
(560, 558, work)
(561, 556, image)
(562, 556, image)
(563, 1, work)
(564, 563, work)
(565, 1, work)

I have a function that will traverse this tree, summoning lists of tuples 
at each leaf. Well and good; it took a lot of trial and error, but it was 
a fine education in tree traversal.

def makeHeirarchy(id):
     id = parentPath(id)[-1]
     rootimages = getImages(id[0])
     rootworks = getWorks(id[0])
     heirarchy = treeTraversal(rootworks, [id, rootimages])
     return heirarchy

## which calls this recursive function:

def treeTraversal(listIn,result):
     for x in listIn:
         if not getWorks(x[0]):
             treeTraversal(getWorks(x[0]), result)
     return result

My problem is that this returns the tuples to me in a flat list.
I've been trying to work out how I can get it to return some sort of 
nested structure: nested lists, dictionaries, or html thus:

     <li>555, 1, image</li>
     <li>556, 1, data<li>
         <li>557, 556, image</li>
         <li>561, 556, image</li>
         <li>562, 556, image</li>
         <li>558, 556, data</li>
             <li>559, 558, image</li>
             <li>560, 558, image</li>
     <li>563, 1, data</li>
             <li>564, 563, data</li>
     <li>565, 1, data</li>

More information about the Tutor mailing list