[Tutor] treeTraversal, nested return?
woodm1979 at gmail.com
Fri Jun 4 20:08:56 CEST 2010
In general, there's 2 solutions to your "unflattening" problem.
A) The general solution: Keep track of the depth you're at, and add
tabs/spaces ('\t' * depth) as necessary.
B) The xml solution: Use (for example) the dom.minidom module, and create a
new "ul node" and populate it with children, at each level. Then, have the
xml do the printing for you.
For what it's worth, I may have a slight nit-pick of your final output. I
don't believe you can technically have a <ul> child of a <ul> node. I'm not
absolutely sure on that, but my quick google searching has appeared to
confirm. If that turns out to be true, you'll need to change the structure
of your output.
All of that is, of course, null and void if you define your own xml scheme.
I enjoy haiku
but sometimes they don't make sense;
On Fri, Jun 4, 2010 at 11:15 AM, <jjcrump at uw.edu> wrote:
> 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)
> rootworks = getWorks(id)
> heirarchy = treeTraversal(rootworks, [id, rootimages])
> return heirarchy
> ## which calls this recursive function:
> def treeTraversal(listIn,result):
> for x in listIn:
> if not getWorks(x):
> treeTraversal(getWorks(x), 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>
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor