[Tutor] How to find descendants recursively?

Fábio Santos fabiosantosart at gmail.com
Sun Jun 16 19:45:41 CEST 2013


On Sun, Jun 16, 2013 at 6:20 PM, Timo <timomlists at gmail.com> wrote:
> I have a datafile which is parsed by an external library, I'm having trouble
> creating a hierarchical structure of the data.
>
> This is what I got so far:
>
> items = get_items() # returns a generator
> for item in items:
>     print(item)
>     children = get_children(item) # also returns a generator
>     for child in children:
>         print("--", child)
>
> This is fine as it will get the children for each parent item. I can't seem
> to figure out how to go further and get the chidren of the children and so
> on.
>
> Thanks.
>

Use recursion to sort this out. Recursion is the technique of calling
the same function you are in, and it's very useful for tree traversal
problems like this one.

def recurse_items(items, dash_count=0):
    for item in items:
        print(('-' * dash_count) + str(item))
        children = get_children(item) # also returns a generator
        if children:
            recurse_items(children, dash_count + 1)

recurse_items(items)

I added a "dash_count" to the mix, so you can see an example of how to
keep track of the level you are in on the tree.

Hope I was of some help. Cheers!

--
Fábio Santos


More information about the Tutor mailing list