# person.py # Walker M. White (wmw2) # October 15, 2015 """Rewrite of person class to turn functions into methods""" import sys # Allow us to go really deep sys.setrecursionlimit(999999999) class Person(object): """Instance represents a person in a genealogical tree. Attributes: fname: First Name [str] lname: Last Name [str] mom: Mother [Person, None if not known] dad: Father [Person, None if not known]""" def __init__(self,fname,lname,mom=None,dad=None): """Creates a new instance of person Parameter fname: The first name Precondition: fname is a string Parameter lname: The last name Precondition: lname is a string Parameter mom: The mother of this person (optional) Precondition: mom is a Person or None Parameter dad: The father of this person (optional) Precondition: dad is a Person or None""" self.fname = fname self.lname = lname self.mom = mom self.dad = dad def __str__(self): """Returns: a string representation of this person""" result = '(Person: '+self.name() if not self.mom is None: result += '; mom: '+self.mom.name() if not self.dad is None: result += '; dad: '+self.dad.name() return result+')' def __repr__(self): """Returns: an unambigious string representation of this person""" return str(self) def name(self): """Returns: the full name of this person""" return self.fname+' '+self.lname # Recursive METHODS def num_ancestors(self): """Returns: number of known ancestors of this person Does not include self, so the answer might be 0.""" # Base case if self.mom == None and self.dad == None: return 0 # Recursive step moms = 0 if not self.mom == None: # Do not forget to include mom as well. moms = 1+self.mom.num_ancestors() dads = 0 if not self.dad == None: # Do not forget to include dad as well. dads = 1+self.dad.num_ancestors() return moms+dads def num_with_name(self,name): """Returns: number of people with name as a first name. This function does not just check ancestors; it checks this person as well. Parameter name: The name to match Precondition: name is a string""" # Check we match match = 0 if self.fname == name: match = 1 # Base case if self.mom == None and self.dad == None: return match # Recursive step moms = 0 if not self.mom == None: # No need to check mom; handled in recursive call. moms = self.mom.num_with_name(name) dads = 0 if not self.dad == None: # No need to check dad; handled in recursive call. dads = self.dad.num_with_name(name) return moms+dads+match