[Tutor] treeTraversal, nested return?
woodm1979 at gmail.com
Sat Jun 5 18:24:56 CEST 2010
On Fri, Jun 4, 2010 at 7:40 PM, <jjcrump at uw.edu> wrote:
> sorry for responding to you instead of the list
> Thanks for trying to tutor the dunderheaded. It is exactly the general
> solution I wish to learn. But how, in the context of my treeTraversal
> function, does one "keep track of the depth you're at"? Tabs are all very
> well, but what I want is truly a nested structure, and as you point out in
> <nitpick> that's not what I was showing in my html (though deprecated,
> browsers still render lists like the one I showed).
> The simplest and most graphic example would be a nested list of lists, but
> for the life of me I can't work out how to generate that in this context.
> On Fri, 4 Jun 2010, Matthew Wood wrote:
> 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.
Spir's example demonstrates the idiom. Watch the "level" variable. During
our function, it gets incremented, and then passed into the next recursive
call. Thus, each call to the recursive function is passing along the
appropriate tab depth level.
Good luck yo. Recursion is one of those concepts that just clicks one day.
At least that's how it is for me.
I'll attempt to provide a pseudo pseudo code description:
def recursive_func(data, indent_level):
print '\t' * indent_level + string_format(data)
# now we know it's not a node, so it must be a child list.
for sub_data in data:
recursive_func(sub_data, indent_level + 1)
Again, watch the indent_level variable.
I enjoy haiku
but sometimes they don't make sense;
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor