""" count_family_tree.py using a family tree graph as an example of recursion $ python count_family_tree.py The top of the tree is in countDescendants, looking at Mary in countDescendants, looking at Sue answer for Sue is 1 in countDescendants, looking at Jane in countDescendants, looking at Sarah answer for Sarah is 1 in countDescendants, looking at Betty answer for Betty is 1 answer for Jane is 3 in countDescendants, looking at Amy answer for Amy is 1 answer for Mary is 6 total number of people is 6 Jim M | Nov 2013 | MIT License """ class Person(object): def __init__(self, name): self.name = name self.kids = [] def addKid(self, kid): self.kids.append(kid) def __str__(self): kids_names = "" for kid in self.kids: kids_names = kids_names + kid.name + "," return "".format( self.name, kids_names) def makeTree(): """ Make the family tree that Jim put on the board""" mary = Person("Mary") for childname in ['Sue', 'Jane', 'Amy']: mary.addKid(Person(childname)) jane = mary.kids[1] for childname in ['Sarah', 'Betty']: jane.addKid(Person(childname)) return mary def countDescendants(person): """ Return count of this person and descendants, i.d. 1 + number of children and children of children etc for this person """ print " in countDescendants, looking at ", person.name count = 1 # this person for kid in person.kids: count = count + countDescendants(kid) print " answer for {} is {}".format(person.name, count) return count def main(): root = makeTree() print "The top of the tree is ", str(root) totalPeopleCount = countDescendants(root) print "total number of people is ", totalPeopleCount main()