0

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
  • 2
    Since you're using recursion anyway, why not make level a parameter to traverse too? Commented Aug 13, 2010 at 7:17
  • Ah, that's a good idea. I got the code from Google and traverse.level was always a little fuzzy to me. I'll add a example with a parameter. Commented Aug 13, 2010 at 7:27

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.