Victor Subervi wrote:
On Thu, Dec 31, 2009 at 12:19 PM, MRAB <pyt...@mrabarnett.plus.com> wrote:

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.


Yeah, that's what level is for *now*. But I need to change that to nest
menus.

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


How do you concatenate a tuple? If we append tree, we can't concatenate it,
can we?
beno

You can't concatenate a tuple; tuples are immutable. Fortunately, tree is a list, which you can concatenate together. Either use extend(), which I suggested earlier, or use +=, as MRAB says above.

    tree.extend(printTree(...))

DaveA

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to