Not Incrementing

MRAB python at mrabarnett.plus.com
Thu Dec 31 12:19:15 EST 2009


Victor Subervi wrote:
> Hi;
> This "pseudo-code" snippet was given to me by Dennis on this list (whose 
> last name escapes me):
> 
> def printTree(allTrees, level=0):
>   tree = []
>   for aTree in allTrees:
>     for name in sorted(aTree.keys()):
>       tree.append("%s%s" % ("\t" * level, name))
>       printTree(aTree[name], level + 1)
>   return tree
> 
> The code returns all the categories ("name") just fine. It doesn't, 
> however, increment level. I know from my tests that printTree is only 
> called twice (once for each store) and about half a dozen times 
> recursively within one of those stores. Why doesn't this increment? Full 
> code follows.
[snip]

'level' is the amount by which the items should be indented. It doesn't
need to be incremented for each item (if that's what you mean). When
'printTree' calls itself to print a subtree, it passes in level + 1 so
that the items in the subtree will be indented by one more level.

The function looks slightly wrong to me because it's appending items to
a list and returning that list, but ignoring the result of printing the
subtree when it calls itself. Perhaps it should be this:

def printTree(allTrees, level=0):
     tree = []
     for aTree in allTrees:
         for name in sorted(aTree.keys()):
             tree.append("%s%s" % ("\t" * level, name))
             tree += printTree(aTree[name], level + 1)
     return tree



More information about the Python-list mailing list