Next / Previous / Contents / Shipman's homepage

9.3. Taxon.childContaining(): Find child containing a descendant

This method finds the child of self that contains a given descendant desc.

xnomo3.py
# - - -   T a x o n . c h i l d C o n t a i n i n g   - - -

    def childContaining ( self, desc ):
        """Find self's child whose subtree contains desc.

          [ desc is a Taxon in self.txny ->
              if desc is a descendant of self ->
                return the child of self containing desc
              else -> raise ValueError ]
        """

A little error checking first: if desc is no deeper than self, it cannot be a descendant of self.

xnomo3.py
        #-- 1 --
        if  desc.rank.depth <= self.rank.depth:
            raise ValueError, ( "Taxon %s is not a descendant of %s." %
                (desc, self) )

At this point we know that desc is deeper than self, so it is safe to assume that the parent of desc is not None. If the parent of desc is self, then desc is the answer—it is the child of self containing desc.

xnomo3.py
        #-- 2 --
        if  desc.parent == self:
            return desc

Recursion simplifies the rest of this method: either desc.parent is a child of self, or a node further up the tree.

xnomo3.py
        #-- 3 --
        # [ if desc.parent is a descendant of self ->
        #     return the child of self containing parent
        #   else -> raise ValueError ]
        return self.childContaining ( desc.parent )