tags:

views:

29

answers:

1

Hello,

I have this python code that will traverse a tree structure. I am trying to add ul and li tags to the function but I am not very succesful. I though I was able to keep the code clean without to many conditionals but now I ain't so sure anymore.

def findNodes(nodes):

    def traverse(ns):
        for child in ns:
            traverse.level += 1
            traverse(child.Children)
            traverse.level -= 1

    traverse.level = 1
    traverse(nodes)

This is the base function I have for traversing my tree structure. The end result should be nested ul and li tags. If need I can post my own not working examples but they might be a little confusing.

Update: Example with parameter

def findNodes(nodes):

    def traverse(ns, level):
        for child in ns:
            level += 1
            traverse(child.Children, level)
            level -= 1

    traverse(nodes, 1)
+2  A: 

I removed the unused level parameter. Adding in any sort of text is left as an exercise to the reader.

def findNodes(nodes):
    def traverse(ns):
        if not ns:
            return ''

        ret = ['<ul>']
        for child in ns:
            ret.extend(['<li>', traverse(child.Children), '</li>'])
        ret.append('</ul>')
        return ''.join(ret)

    return traverse(nodes)
Aaron Gallagher
Thanks, that looks really good. But doesn't it leave me with an empty <ul> if there are no children?
Pickels
I fixed it, if you really care about that.
Aaron Gallagher
I really liked your answer. Thanks again!
Pickels