[Tutor] How to find descendants recursively?

Alan Gauld alan.gauld at btinternet.com
Sun Jun 16 19:56:46 CEST 2013


On 16/06/13 18:20, Timo wrote:

> 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.

Presumably you can call get_children on each child?

       children = get_children(item) # also returns a generator
       for child in children:
           grandchildren = get_children(child)

If you don't know how many levels it goes down the normal approach is to 
use recursion to define a function that get called until the result is 
empty. If there are too many layers for recursion then you will need to 
keep a flag to count the layers and create/manage the heirarchy pointer 
for you.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list